【问题标题】:How to write code to get the AWS cognito access token?如何编写代码来获取 AWS cognito 访问令牌?
【发布时间】:2019-10-16 03:48:21
【问题描述】:

我有一个 POSTMAN 查询来获取我们端点的访问令牌。邮差查询是: phmo-test/auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials 授权有客户端 ID 和客户端 Secret。它工作得很好,并返回给我访问令牌。 我必须将此 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)

这不是返回状态码。我做错了什么?

【问题讨论】:

    标签: token amazon-cognito


    【解决方案1】:

    Python 有一个很棒的库,您可以使用它来简单地处理事情。 您可以使用 boto3 中的 initiate_auth 来获取所有令牌。您需要在 authflow、客户端 ID 和用户凭据中指定 USER_PASSWORD_AUTH。

    更新: 这是 initaite_auth 的一个例子

    logn = boto3.client('cognito-idp')
    res = logn.initiate_auth(
                UserPoolId='poolid', 
                ClientId='clientid',
                AuthFlow='USER_PASSWORD_AUTH',
                AuthParameters={
                    'USERNAME': username,
                    'PASSWORD': password
                }
            )
    print(res)
    

    您必须用自己的值替换 poolid、clientid、用户名和密码,这应该可以。

    【讨论】:

    • 你能解释一下initate auth吗?
    【解决方案2】:

    文档中没有最清楚地解释,但它在那里: https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html

    这是您可以使用客户端凭据流从 Cognito OAuth2.0 获取令牌的方式:

    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())
    

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2020-11-20
      • 2018-04-11
      • 1970-01-01
      • 2018-04-01
      • 2020-10-27
      • 2021-01-05
      • 2021-12-21
      相关资源
      最近更新 更多