django处理基本http身份验证
目前,我有以下代码来处理传入的GET请求:django处理基本http身份验证,django,django-rest-framework,django-views,django-request,Django,Django Rest Framework,Django Views,Django Request,目前,我有以下代码来处理传入的GET请求: #view.py def handle_request(request): if request.method == 'GET': <do something> return response 但现在我想添加基本的http身份验证: curl --user username:password http://some_url/ 我想修改views.py代码,使其看起来像: def handle_r
#view.py
def handle_request(request):
if request.method == 'GET':
<do something>
return response
但现在我想添加基本的http身份验证:
curl --user username:password http://some_url/
我想修改views.py代码,使其看起来像:
def handle_request(request):
if request.method == 'GET':
if username == some_hard_coded_approved_username and password == corresponding_password:
<do something>
return response
else:
response = HttpResponse("")
response.status_code = 401
return response
您应该为用户分配特定的权限。 检查用户是否经过身份验证,是否具有权限。如果上述条件成立,则应执行代码块 大概是这样的:
def handle_request(request):
if request.method == 'GET':
if request.user.is_authenticated and user.has_perm('custom_permission'):
<do something>
return response
else:
response = HttpResponse("")
response.status_code = 401
return response
def handle_请求(请求):
如果request.method==“GET”:
如果request.user.com已通过身份验证且user.com具有“自定义权限”:
返回响应
其他:
响应=HttpResponse(“”)
response.status_code=401
返回响应
您应该避免在代码中直接使用用户名和密码,因为如果您将其放在任何vcs中,任何人都可以看到您的用户密码并侵入您的系统
有关django权限,请转到解决:
对于以下命令:
curl -H "Authorization: username_in_curl_cmd password_in_curl_cmd" http_url
以下代码处理基本http身份验证:
#views.py
def handle_request(request):
if 'HTTP_AUTHORIZATION' in request.META:
[user, password] = request.META['HTTP_AUTHORIZATION'].split(" ")
# user = username_in_curl_cmd
# password = password_in_curl_cmd
if user == some_enivorment_variable and password == some_enivorment_variable
and request.method == 'GET':
<do something>
return response
return 401 response
#views.py
def处理请求(请求):
如果request.META中有“HTTP_AUTHORIZATION”:
[user,password]=request.META['HTTP_AUTHORIZATION'].split(“”)
#user=username\u在\u curl\u cmd中
#password=password\u在\u curl\u cmd中
如果user==some\u enivorment\u变量和password==some\u enivorment\u变量
和request.method==“GET”:
返回响应
返回401响应
@驱逐者的评论为我指明了正确的方向。挑战在于找出“HTTP_u”在标题前面,并且标题被转换为大写。尝试request.META['username']和checkI在我的views.ppy中添加了print(request.META['username']),但这只导致了一个500错误。您需要将它放在请求之后。method=GET lineNo progress@Exprator,我把它放在方法==GET行之后。这是我正在使用的curl命令:curl--user dusername:dpassword您需要在curl中使用username=username和password=password这不是我正在寻找的解决方案。我希望用户能够使用一条命令行指令访问我的服务器,我希望能够使用一条命令行指令中的信息对用户进行身份验证如果我要使用此解决方案,那么用户首先必须登录我的网站,然后使用cookie中的信息对自己进行身份验证在命令行中发出GET请求时。
curl -H "Authorization: username_in_curl_cmd password_in_curl_cmd" http_url
#views.py
def handle_request(request):
if 'HTTP_AUTHORIZATION' in request.META:
[user, password] = request.META['HTTP_AUTHORIZATION'].split(" ")
# user = username_in_curl_cmd
# password = password_in_curl_cmd
if user == some_enivorment_variable and password == some_enivorment_variable
and request.method == 'GET':
<do something>
return response
return 401 response