3
votes

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?

3

3 Answers

6
votes

You do not need API Gateway Custom Authorizer ... just to authenticate a API end point - Goto its Method Request and select AWS_IAM for Authorization dropdown .. where NONE is by default selected ...

when the access token is send to this end point - it will AUTOMATICALLY check the access token Role (after communicating with cognito service) and check the policies attached with the Role.

if the IAM policy allows to invoke this end point - AWS API will execute it further else it will throw you back with 403 Error or Some Error

YOU DO NOT NEED TO WRITE ANY CODE - UNLESS you have some totally different auth logic to be applied - which can be achieved via "API Gateway Custom Authorizer"

1
votes

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

You should create Cognito Authorizer (Available as a option when you create a custom authorizer) and link your User pool & Identity Pool, Then the client needs to send idToken (generated using User pool SDK) to access endpoint. This idToken will get Validated by the Cognito Identity Pool via Coginito Authorizer (Used in Authorization Method dropdown).

idToken getting generated by SDK can be done using another lambda+endpoint like login endpoint or it can be generated using cognito mobile sdk's as well.