Python请求:使用Oauth2密码身份验证流的自定义身份验证似乎不起作用

2024-05-23 20:07:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用请求实现OAuth2密码流身份验证过程。然后,我依赖于自定义身份验证方法,因为我找不到任何内置方法。有吗? 然而,虽然准备好的请求看起来很好,但最终的请求似乎没有收到标题,因为我得到了一个“未授权”错误

这是我的密码:

import requests
import os

from requests.auth import AuthBase

username= os.environ['ADMIN_LOGIN'],
password= os.environ['ADMIN_PWD'],

class CustomAuth(AuthBase):
    """Attaches Oauth2 password Authentication to the given Request object."""
    def __init__(self, username, password):
        # setup any auth-related data here
        auth_response = requests.post(
            url = os.environ['APP_URL'] +'/api/v1/login/access-token',
            data = {
                'username': username,
                'password': password,
            }
        ).json()
        self.token = auth_response['access_token']

    def __call__(self, r):
        # modify and return the request
        r.headers['Authorization'] = 'bearer ' + self.token
        print(r.headers)
        return r

response = requests.get(
    url = os.environ['APP_URL'] +'/api/v1/orders',
    auth= CustomAuth(username, password)
)
print(response, response.content)

输出:

{'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MjM3NDczNjgsInN1YiI6IjEifQ.UVDa1sfbbWByXkUWGFqSrLIN9L-0JKNepUm9BZBe5SE'}
<Response [401]> b'{"detail":"Not authenticated"}'

Tags: 方法importselftokenauth身份验证密码admin