AWS CLI - how to generate security tokens for a cognito user

Here's the AWS CLI command to authenticate and receive an auth token:

aws cognito-idp initiate-auth --region YOU_REGION --auth-flow USER_PASSWORD_AUTH --client-id YOUR_CLIENT_ID --auth-parameters USERNAME=YOUR_EMAIL,PASSWORD=YOUR_PASSWORD

Example

aws cognito-idp initiate-auth --region us-west-2 --auth-flow USER_PASSWORD_AUTH --client-id 7f2spb636ptn074on1pdjgnk9l --auth-parameters [email protected],PASSWORD=Z3qj88WTJCi9DX6RRVFWtdv

Response

{
    "ChallengeParameters": {},
    "AuthenticationResult": {
        "RefreshToken": "eyJjdH......89kXQjZ9thA",
        "AccessToken": "eyJra......xB9eQ",
        "ExpiresIn": 3600,
        "TokenType": "Bearer",
        "IdToken": "eyJraWQiOiJh....PfRUcDeEw"
    }
}

If you get the error {"__type":"InvalidParameterException","message":"USER_PASSWORD_AUTH flow not enabled for this client"}, you need to enable USER_PASSWORD_AUTH.

Go to your AWS Cognito dashboard -> "App Clients" -> "Show Details" -> check the box "Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH)"


It works for me. I can't see any difference with yours

Terminal Screenshot

Are you using the app client id that you created at User Pool 'App clients' sections (not at federated identity section) ? If so, is this option checked ?

Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH)

I am using the token starting after 3600 till the next whitespace. Put it on postman header and call lambda behind Cognito Authorizer.

UPDATE

If anyone interested in single command shell script version of this -> Bash Script

I use it quite often