OAuth 2 Authlib。如何访问资源?

时间:2018-10-17 10:28:45

标签: python flask oauth-2.0 authlib

我已经设置了this个示例OAuth2服务器。它具有授权和一个资源(/api/me)。我也在python中制作客户端应用程序。我想通了如何获得令牌。但是,当我尝试访问/api/me时,会收到响应{"message":"401 Unauthorized: None"}。我可以说我将令牌作为参数放在URL中,也将其放在FORM中。它放在access_token键下。我究竟做错了什么?显然它应该以某种方式工作?

这是我的客户端应用代码:

    def token_get():
    token = None
    print("========================================")
    print("Sending POST request to get token")
    # FORM data
    payload = {
        "client_id":"ySFTzBKLo0XTaK2tQL9ls4Fc",
        "client_secret":"vq8vMZplY4J00FrxKx4ynV2mhmL2zzjMzP1U2bXZPhQRcmJl",
        "grant_type":"password", 
        "scope":"profile",
        "username":"ignas",
        "password":"valid"
    }
    auth=(
        "ySFTzBKLo0XTaK2tQL9ls4Fc",
        "vq8vMZplY4J00FrxKx4ynV2mhmL2zzjMzP1U2bXZPhQRcmJl"
    )
    r = requests.post(_url(f"/oauth/token"), data=payload, auth=auth)
    print(f"RESPONSE {r.status_code}")
    print(f"r.url={r.url}")
    print(f"r.text={r.text}")
    if r.status_code == 200:
        json = r.json()
        print(f"JSON=\"{json}\"")
        token = json["access_token"]
        print(f"TOKEN=\"{token}\"")
    print("========================================")

    return token

def api_me_get(token):
    print("========================================")
    print("Sending GET request to get protected data of me")
    # FORM data
    payload = {
        "access_token":f"{token}"
    }
    print(f"PAYLOAD=\"{payload}\"")
    r = requests.get(_url(f"/api/me"), data=payload, params=payload)
    print(f"RESPONSE {r.status_code}")
    print(f"r.url={r.url}")
    print(f"r.text={r.text}")
    if r.status_code == 200:
        json = r.json()
        print(f"JSON=\"{json}\"")
    print("========================================")

def test_token():
    token = token_get()
    api_me_get(token)

def main():
    test_token()

main()

0 个答案:

没有答案