【问题标题】:django handling basic http authdjango 处理基本的http auth
【发布时间】:2018-08-28 20:23:11
【问题描述】:

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

【问题讨论】:

  • 尝试 request.META['username'] 并检查
  • 我在 views.ppy 中添加了 print(request.META['username']) 但这只是导致 500 错误
  • 需要放在request.method=GET这一行之后
  • 没有进展@Exprator,我把它放在方法 == GET 行之后。这是我正在使用的 curl 命令: curl --user dusername:dpassword some_url
  • 你需要在 curl 中使用 username=username 和 password=password

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


【解决方案1】:

您应该为用户分配一定的权限。 检查用户是否已通过身份验证以及他是否具有权限。如果上述条件成立,那么您应该执行代码块。

类似这样的:

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

【讨论】:

  • 这不是我正在寻找的解决方案。我希望用户能够使用单个命令行指令来访问我的服务器,并且我希望能够使用单行命令指令中的信息对用户进行身份验证
  • 如果我要使用这个解决方案,那么首先用户必须登录我的网站,然后在命令行中发出 GET 请求时使用来自 cookie 的信息来验证他/她自己。跨度>
【解决方案2】:

已解决:

对于以下命令:

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 的 cmets 为我指明了正确的方向。挑战在于弄清楚“HTTP_”被添加到标题中,并且标题被转换为大写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    相关资源
    最近更新 更多