Reputation: 355
I am trying to implement API Gateway authentication using Cognito Access Token from an authenticated user, as shown in the video -> https://www.youtube.com/watch?v=bj3yVT6j3XU
To get the access token I am performing 2 methods:
1) Getting “Access Token” with Hosted UI + Code + Postman:
In the cognito user pool, I access the Hosted UI in the “App Client Configurations”:
After clicking the button above, and signing up with an existing user, I get the code in the url, as shown below:
With this code, I go to postman and can have access to the access token, as shown below:
Still using Postman, I call the API url with the header containing the “Authorization”, and I successfully get the response:
2) Getting “Access Token” with Auth method in React js:
I already tried to get the access token using the Auth.currentAuthenticatedUser() and Auth.currentSession(), and I realized they are the same. So here I am going to show the access token from the Auth.curentAuthenticatedUser().
When I try to use this access token in the react js code it doesn’t work, and I get the following error:
When I try to use this access token in the Postman, it also doesn’t work:
When I use the access token from the Hosted UI in the React js code, it works perfectly:
My questions are:
• Why I am getting different “Access Token”?
• How can I get the right access token in the React Js?
Upvotes: 2
Views: 1234
Reputation: 355
I found the solution - credits to Chirag from SrceCde.
The API call was "unauthorized" when I was using the AccessToken from the Amplify on React JS, due to scope.
The accessToken is generated with aws.cognito.signin.user.admin scope, as show the image below:
For that reason, it is necessary to enable the "aws.cognito.signin.admin" OAuth scope in the Cognito User Pool, and also consider the "aws.cognito.signin.admin" OAuth scope in the API Gateway for the API you want to call.
After doing that, you can get the accessToken with the Auth.currentAuthenticatedUser() method, as I was already doing.
Upvotes: 1