Jose Guilherme
Jose Guilherme

Reputation: 355

Cognito Access Token + API Gateway Authentication - (Hosted UI vs Auth method on React js) returning different values from the same session

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
enter image description here

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”: enter image description here

After clicking the button above, and signing up with an existing user, I get the code in the url, as shown below: enter image description here

With this code, I go to postman and can have access to the access token, as shown below: enter image description here

Still using Postman, I call the API url with the header containing the “Authorization”, and I successfully get the response: enter image description here

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(). enter image description here

When I try to use this access token in the react js code it doesn’t work, and I get the following error: enter image description here

When I try to use this access token in the Postman, it also doesn’t work: enter image description here

When I use the access token from the Hosted UI in the React js code, it works perfectly: enter image description here

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

Answers (1)

Jose Guilherme
Jose Guilherme

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: enter image description here 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. enter image description here enter image description here

After doing that, you can get the accessToken with the Auth.currentAuthenticatedUser() method, as I was already doing.

Upvotes: 1

Related Questions