我有一个 POSTMAN 查询来获取我们端点的访问 token 。 POSTMAN 邮政查询是: phmo-test/auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials 授权有客户端ID和客户端Secret。它工作得很好并返回我访问 token 。 我必须将此 POSTMAN 查询转换为 python 代码。我认为这很简单,就像使用 REQUESTS 库编写任何其他 POST 查询一样,但它似乎不起作用。
base_url = 'http://phmo-test.auth.us-east-1.amazoncognito.com/oauth2/token'
client_id=<my client ID>
client_secret=<My client secret>
grant_type='client_credentials'
headers = {'Content-Type':'application/x-www-form-urlencoded',
'cookie':'XSRF-TOKEN=27293445-d70d-4907-bfc5-62ba8a84697c'}
response = requests.post(base_url,
auth={'Username':client_id, 'Password':client_secret},
params={'grant_type':grant_type},
headers = headers)
print("WAHHHHHHHHHHHHHHHHHHH",response.status_code)
这不会返回我的状态代码。我做错了什么?
最佳答案
文档中没有最清楚地解释,但它就在那里: https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
这是您如何使用客户端凭据流程从 Cognito OAuth2.0 获取 token 的方法:
import base64
import requests
oauth_base_url = "https://YOUR_THING.auth.eu-west-1.amazoncognito.com/oauth2/token"
client_id = "get_from_cognito"
client_secret = "get_from_cognito"
grant_type = "client_credentials"
scope = "scope_namespace/scope_name" # defined in Cognito
# Base64 encode auth info and add to headers
auth_b64 = base64.b64encode(f"{client_id}:{client_secret}".encode())
oauth_headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Basic {auth_b64.decode('utf-8')}",
}
# Message body is text as docs define:
oauth_payload_txt = f"""grant_type={grant_type}&
client_id={client_id}&
scope={scope}
"""
# Post returns JSON with "access_token" as the Bearer token.
resp = requests.post(oauth_base_url, headers=oauth_headers, data=oauth_payload_txt)
print(resp.json())
关于token - 如何编写代码来获取AWS cognito访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56379077/