在烧瓶中请求授权

Swa*_*nil 3 python werkzeug flask python-2.7

我正在开发一个 Flask 应用程序,它调用在 Flask 中开发的 REST 服务。目标 REST 服务方法使用基本身份验证进行保护。我发现对于这种类型的身份验证,我必须使用 base64 编码。我正在尝试以这种方式将凭据传递给服务:

headers = {'username': base64.b64encode(g.user['username'])}
response = requests.post('http://127.0.0.1:3000/api/v1.0/follower/' + username, headers=headers)
Run Code Online (Sandbox Code Playgroud)

在服务端,用户名被提取为:

user_name = request.authorization.username
Run Code Online (Sandbox Code Playgroud)

但是,该服务无法对提供的凭据进行授权,并且会引发错误 401。服务端和应用程序端的授权是否存在任何问题?

Mar*_*ers 8

您没有创建正确的基本授权标头。

您必须调用 header Authorization,然后将 header 值设置为 string Basic <base64-of-username-and-password-separated-by-a-colon>

如果我们假设密码为空,则如下所示:

headers = {
    'Authorization': 'Basic {}'.format(
        base64.b64encode(
            '{username}:{password}'.format(
                username=g.user['username'],
                password='')
        )
    ),
}
Run Code Online (Sandbox Code Playgroud)

请参阅协议客户端的维基百科描述

但是,不需要手动构建它,因为requests当您将用户名和密码作为元组传递给auth关键字时,将为您创建标头:

response = requests.post(
    'http://127.0.0.1:3000/api/v1.0/follower/' + username,
    auth=(g.user['username'], ''))
Run Code Online (Sandbox Code Playgroud)