【问题标题】:How does Python contact AWS Cognito Token endpoint with Authorization CodePython 如何使用授权码联系 AWS Cognito 令牌端点
【发布时间】:2021-07-12 01:49:00
【问题描述】:

我正在尝试调用 AWS Cognito 令牌端点以将我的授权代码转换为三个 JWT。我有这个设置并在 Postman 中工作,但不是在 Python 中。下面是我使用的 Python 代码,虽然我从 AWS 收到了{"error":"invalid_request"}。我应该如何修改 Python 代码以获取 JWT?

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 之间的值匹配。请求标头包含具有正确值的 Content-Type 和 Authorization。我花了大约 3 个小时在这上面并没有通过这一点,尽管我所有的搜索都表明我正在正确地实现请求。

回复:

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

非常感谢任何帮助。

【问题讨论】:

  • 我曾经做过类似的实现。我看到我的实现和你的实现的唯一区别是通过了身份验证详细信息。我按照 AWS 的建议以 base64 格式传入了授权密钥中的标头。您可以尝试在标题中传递它吗? docs.aws.amazon.com/cognito/latest/developerguide/…

标签: python python-3.x amazon-web-services jwt amazon-cognito


【解决方案1】:

如果有帮助,我尝试回答这个here,但这里是用于逐步了解大部分逻辑的 sn-p

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)

【讨论】:

  • 我在有效负载部分缺少客户端 ID,我仅将其包含在基本身份验证标头中。这帮助我注意到:) ty
猜你喜欢
  • 2018-09-26
  • 2018-04-11
  • 2022-11-15
  • 2019-11-13
  • 2021-11-05
  • 2020-11-25
  • 2019-10-15
  • 2023-01-19
  • 1970-01-01
相关资源
最近更新 更多