django处理基本的http auth

时间:2018-03-20 05:52:44

标签: django django-rest-framework django-views django-request

目前我有以下代码来处理传入的GET请求:

#view.py
def handle_request(request):

    if request.method == 'GET':
        <do something>
        return response

此代码可以处理以下形式的简单GET请求:

curl http://some_url/

但现在我想添加基本的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

如何实现此行以解析来自http请求的用户名和密码:

if username == some_hard_coded_approved_username and password == corresponding_password:

3 个答案:

答案 0 :(得分:0)

您应该为用户分配一定的权限。 检查用户是否经过身份验证并且是否拥有该权限。如果上述条件成立,则应执行代码块。

这样的事情:

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

您应该避免在代码中直接使用用户名和密码,因为如果您将其放在任何vcs中,任何人都可以看到您的用户密码并入侵您的系统。

对于django权限,请转到here

答案 1 :(得分:0)

假设您正在使用Django RestFramework 更改view功能,如下所示,以有效地执行身份验证过程,

from django.contrib.auth.decorators import permission_required
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import api_view


@api_view()
@permission_required([IsAuthenticated, ], raise_exception=True)
def basic_auth_view(request, format=None):
    if request.method == 'GET':
        return Response(data={"msg": "permission granded"})



你的CURL请求将是这样的,

curl --user username:password http://host/api/endpoint/

答案 2 :(得分:0)

解决:

用于以下命令:

curl -H "Authorization: username_in_curl_cmd password_in_curl_cmd" http_url

以下代码处理基本的http auth:

#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

@ Exprator的评论指出了我正确的方向。挑战在于确定标题前面有'HTTP_',并且标题被转换为大写。