How to generate access token for an AWS Cognito user?

geekprogrammer picture geekprogrammer · Mar 2, 2018 · Viewed 22.4k times · Source

I' using Cognito user pool for securing my API gateway . Now I would like to make requests to my API using postman but I need to pass in Authorization token as the API is secured. Is there any AWS CLI command or REST API to generate auth tokens(by passing username/password)? I have searched documentation but couldn't find any examples. Thanks for your help.

Answer

shenku picture shenku · Aug 14, 2018

You can do this using the following CLI commands:

Register a user

aws cognito-idp sign-up --region {your-aws-region} --client-id {your-client-id} --username [email protected] --password password123

Confirm user registration

aws cognito-idp admin-confirm-sign-up --region {your-aws-region} --user-pool-id {your-user-pool-id} --username [email protected]

Authenticate (get tokens)

aws cognito-idp admin-initiate-auth --region {your-aws-region} --cli-input-json file://auth.json

Where auth.json is:

{
    "UserPoolId": "{your-user-pool-id}",
    "ClientId": "{your-client-id}",
    "AuthFlow": "ADMIN_NO_SRP_AUTH",
    "AuthParameters": {
        "USERNAME": "[email protected]",
        "PASSWORD": "password123"
    }
}

You should get a response like this if everything is set up correctly:

{
    "AuthenticationResult": {
        "ExpiresIn": 3600,
        "IdToken": "{your-idtoken}",
        "RefreshToken": "{your-refresh-token}",
        "TokenType": "Bearer",
        "AccessToken": "{your-access-token}"
    },
    "ChallengeParameters": {}
}