Search code examples
amazon-web-servicesaws-lambdaaws-api-gatewayamazon-cognito

How to get validate Cognito Access Token in AWS Lambda to allow Gateway API call?


What I am trying to do is to set up API Gateway to my Lambda function that saves some in DynamoDB (or other stuff that I want to be only for logged in users). But I do not understand how to validate AccessToken and how to get user from that.

I found this post on AWS forum and I decided to try approach 1.

Cognito User Pools + API Gateway + API Gateway Custom Authorizer + Cognito User Pools Access Token.

So now I have logged in user :

var authenticationData = {
  Username : 'username', // your username here
  Password : 'password', // your password here
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
    console.log('access token + ' + result.getAccessToken().getJwtToken());
....

and his accessToken. I also set up custom API Gateway Custom Authorizer in my API call.

Now I should validate the access token and decide whether to allow or deny method call. But I do not understand how to do that and how to retrieve user from the token?


Solution

  • Please take a look at the sample code on this blog post: https://mobile.awsblog.com/post/Tx3JK25U7Z9EUIU/Integrating-Amazon-Cognito-User-Pools-with-API-Gateway