hous
hous

Reputation: 150

How to make AWS Cognito User Data available to Lambda via API Gateway, without an Authorizer?

I have a website that uses AWS Cognito (via Amplify) for user login. The API is on a separate stack that deploys with Serverless.

I am trying to have an API endpoint that can access the current logged-in user's Cognito User Pool data (username, email) if it is available. The only way I've been able to achieve this is by using a cognito user pool authorizer via API Gateway.

Example:

functions:
  getMe:
    handler: /endpoints/myService.get
    events:
      - http:
          path: /myService
          method: GET
          cors: true
          authorizer:
            type: COGNITO_USER_POOLS
            authorizerId: ${self:custom.apiGatewayAuthorizerId.${self:custom.stage}}

Where authorizerId is set to the 6-character Authorizer ID found on the AWS Console's API Gateway Authorizers page. However, this blocks all traffic that is not authenticated with Cognito. That isn't what I want, since I have a number of services that should be accessible by both anonymous and logged-in users. I just want to personalize the data for users that are logged-in.

Is there any way to allow traffic and pass the cognito user parameters through the API Gateway to Lambda if they are available?

All resources I've been able to find regarding Cognito + API Gateway + Lambda are specifically about restricting access to endpoints and not layering on data to the requests...

Upvotes: 1

Views: 991

Answers (1)

Imran Arshad
Imran Arshad

Reputation: 4012

Based on comments above you want Anonymous and Logged-in users pass through same gateway end point ?

You can still use the same setup but remove the authentication from API Gateway and take the logic in your application.

If users try to access your services while being logged in AWS amplify will send through the Authorization header with Id token to API Gateway and API Gateway will pass this header as it is to the application. You will have to check inside your application for this Authorization header and crack open Id token passed to find the user claims/attributes and do your logic. For any other user that doesn't have this token can be considered anonymous.

You still need to Validate the token if you find one in request to make sure it's a valid token and extract claims/Attributes thereafter.

Upvotes: 1

Related Questions