Skip to main content
 首页 » 编程设计

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

2025年05月04日24yyy_WW

我正在创建一个 View ,该 View 预计会被在 header 中传递用户名和密码的机器人访问。 (具体来说,这是一个谷歌提要机器人)。但是,我似乎永远无法访问用户名和密码来验证机器人的凭据。 request.GET.get('username') 和 request.GET.get('password') 都返回 None 因为 request.GET 和 request.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 字符串。那么这只是隔离用户名和密码的问题。然后进行身份验证。