token - 如何编写代码来获取AWS cognito访问 token ?

标签 token amazon-cognito

我有一个 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/

相关文章:

amazon-web-services - Cognito Lambda 触发套接字超时

amazon-ec2 - 是否可以将 Amazon Cognito 与 LDAP 结合使用?

amazon-web-services - Cognito 登录的 Lambda 函数第一次不起作用

Azure Blob 存储 : token to share access

c++ - 从 session ID 获取正确的 token

authentication - 如何在 API 后端从 AWS Cognito 验证 JWT?

node.js - AWS Cognito 可以在 EB 上的 Node/Express/React 应用程序中使用吗?

token - 在 ERC20 合约中设置代币最大数量的问题

c - 我怎样才能与 C 预处理器连接两次并扩展一个宏,如 "arg ## _ ## MACRO"?

php - 带有 token 模块的 Drupal 自动回复器