python - 在 Django 请求 header 中访问用户名和密码返回 None

标签 python django basic-authentication

我正在创建一个 View ,该 View 预计会被在 header 中传递用户名和密码的机器人访问。 (具体来说,这是一个谷歌提要机器人)。但是,我似乎永远无法访问用户名和密码来验证机器人的凭据。 request.GET.get('username')request.GET.get('password') 都返回 None 因为 request.GETrequest.POST 返回空的 QueryDicts。我正在使用具有基本身份验证的 Postman 来测试我的请求。 这是我来自 views.py 的代码:

def authenticate_bot(request):
    username = request.GET.get('username')
    password = request.GET.get('password')
    feed_bot = authenticate(username=username, password=password)

    if feed_bot is not None:
        # Confirmed as user credentials.
        login(request, feed_bot)

如何从我的基本身份验证 header 中检索用户名和密码?

最佳答案

谢谢nthall为我指明了正确的方向 - 找到 request.META 字典是关键。

由于我找不到太多解释该过程的资源,我将在此处发布从 Authorization header 检索和验证数据的整个 Django 过程。

import base64
from django.contrib.auth import authenticate

def header_auth_view(request):
    auth_header = request.META['HTTP_AUTHORIZATION']
    encoded_credentials = auth_header.split(' ')[1]  # Removes "Basic " to isolate credentials
    decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8").split(':')
    username = decoded_credentials[0]
    password = decoded_credentials[1]
    feed_bot = authenticate(username=username, password=password)
    # if the credentials are correct, then the feed_bot is not None, but is a User object.

Django 将“HTTP_”前缀大写并附加到请求中传递的任何 header ,正如 nthall 正确指出的那样,它可以通过 request.META 访问。

我隔离了 base64 编码信息,其格式为 'Basic username:password',方法是在空格上拆分 header ,因此它只是 'username:password' .然后我使用 base64 解码,然后解码结果以将类似字节的字符串转换为 utf-8 字符串。那么这只是隔离用户名和密码的问题。然后进行身份验证。

关于python - 在 Django 请求 header 中访问用户名和密码返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38016684/

相关文章:

iis - 如何使用基本身份验证将比用户名/密码更多的数据传递给 WCF 4.0 RESTful 服务中的服务方法

python - 适用于 Windows 平台的最新 python 3.3 绑定(bind)版本在哪里?

使用 Pigment 程序突出显示 python 语法

python - pyFMI参数更改不会改变模拟输出

python - 如何在 1.4.2 版本中执行 django syncdb?

python - 静态文件和 django 模板

python - 在 Python 中将时间从 AM/PM 格式转换为军事时间

django - Django 模板中的复杂条件?

ios - ASIHTTPRequest 基本身份验证失败

Perl LWP 手动关闭连接