We setup a Cognito user pool with Oauth 2.0 Implicit Grant as allowed Oauth Flows and want our JS based web application to be able to call lambda functions (which have API Gateway endpoints) with the Cognito JWT token as part of the request Authorization headers. We tested the authentication with Postman by using the default Cognito Hosted UI to enter username and password and then copy-pasting the access_token from the success login URL to Postman. This works fine. However, when we authenticate using the amazon-cognito-identity.min.js SDK function below (our app uses jQuery and not a framework like React), then the authenticateUser function is successfull but with a Cognito response containing the wrong JWT token (the token doesn't work when we copy paste it into Postman for testing the same lambda function as we did successfully with the Hosted UI).
Our JS code looks as follows:
var authentication_details = new AmazonCognitoIdentity.AuthenticationDetails({
Username: email,
Password: $('#password').val(),
});
var cognito_user = new AmazonCognitoIdentity.CognitoUser({
Username: email,
Pool: cognito_user_pool
});
cognito_user.authenticateUser(authentication_details, {
onSuccess: function (result) {
var jwt_token = result.getAccessToken().getJwtToken(); // THIS TOKEN DOES NOT WORK AND IS LONGER THAN THE TOKEN GENERATED BY THE COGNITO HOSTED UI
....
result.getAccessToken().getJwtToken() return "Unauthorized".
We searched online but could not find any hints on why the token would be different when taken from the authenticateUser return parameter. Also, we tested with the ID token using result.getIdToken().getJwtToken() but it doesn't work. What is our mistake? SDK: amazon-cognito-identity.min.js
The Cognito SDK uses the scope aws.cognito.signin.user.admin by default, while the Hosted UI uses the scopes openid profile email.
To make the authenticateUser method work, you would need to make two changes:
More details are available here: https://aws.amazon.com/premiumsupport/knowledge-center/cognito-custom-scopes-api-gateway/