2

目前我有以下代码来处理传入的 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:
4

2 回答 2

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 权限,请到这里

于 2018-03-20T06:29:06.137 回答
0

解决了:

对于以下命令:

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

@Exprator's comments pointed me in the right direction. The challenge was figuring out that 'HTTP_' is prepended to the header and that the header is converted to uppercase.

于 2018-03-20T16:31:30.043 回答