user8882700
user8882700

Reputation: 23

How to write code to get the AWS cognito access token?

I have a POSTMAN query to get the access token for our endpoint. POSTMAN post query is : phmo-test/auth.us-east-1.amazoncognito.com/oauth2/token?grant_type=client_credentials Authorization has client ID and client Secret. And its working perfectly fine and returning me access token. I have to convert this POSTMAN query to python code. I thought it is simple like writing any other POST query using REQUESTS library, but it doesn't seems to be working.

    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)

This is not returning me status code. What am I doing wrong?

Upvotes: 2

Views: 5087

Answers (2)

mireofthedeep
mireofthedeep

Reputation: 31

Not most clearly explained in the docs, but it is there: https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html

This is how you can get a token from Cognito OAuth2.0 using Client Credentials flow:

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

Upvotes: 3

Ninad Gaikwad
Ninad Gaikwad

Reputation: 4480

Python has a great library that you can use to simply things up for you. You can use the initiate_auth from boto3 to get all the tokens. You'll need to specify USER_PASSWORD_AUTH in authflow, client id and user credentials.

UPDATE: Here's an example of 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)

You have to replace poolid, clientid, username and password with your own values and this should work.

Upvotes: 0

Related Questions