Python如何使用授权代码联系AWS Cognito令牌端点

2024-04-25 14:35:47 发布

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

我试图调用AWS Cognito令牌端点,将我的授权代码转换为三个JWT。我已经在Postman中进行了设置和工作,但不是在Python中。下面是我使用过的Python代码,尽管我正在从AWS获得{"error":"invalid_request"}。我应该如何修改Python代码以获得JWTs

import requests

headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
}

data = {
  'grant_type': 'authorization_code',
  'client_id': client_id,
  'code': authorization_code,
  'redirect_uri': redirect_uri,
}

response = requests.post(
  'https://example.auth.us-east-1.amazoncognito.com/oauth2/token',
  json=data,
  auth=(client_id, client_secret),
  headers=headers
)

我已经验证了变量是否包含正确的数据,以及Postman、Python和AWS之间的值是否匹配。请求头包含具有正确值的内容类型和授权。我花了大约3个小时在这个问题上,但还没有通过这一点,尽管我所有的搜索都表明我正确地实现了请求

答复:

400 Client Error: Bad Request for url: https://example.auth.us-east-1.amazoncognito.com/oauth2/token{"error":"invalid_request"}

非常感谢您的帮助


Tags: 代码clientauthawsiddatarequestcode
1条回答
网友
1楼 · 发布于 2024-04-25 14:35:47

如果有帮助的话,我试着回答这个here但是这里有一个片段来逐步介绍大部分逻辑

token_url=f"https://{domain}.auth.us-east-1.amazoncognito.com/oauth2/token"
message = bytes(f"{client_id}:{client_secret}",'utf-8')
secret_hash = base64.b64encode(message).decode()
payload = {
    "grant_type": 'authorization_code',
    "client_id": client_id,
    "code": code,
    "redirect_uri": redirect_uri
}
headers = {"Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Basic {secret_hash}"}
           
resp = requests.post(token_url, params=payload, headers=headers)

相关问题 更多 >