How to connect lambda authorizer to a gateway api? Verifying user in cognito userpool?

Viewed 101

Here is my aws template file:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >

Globals:
  Function:
    Timeout: 3

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: MyLambdaTokenAuthorizer
        Authorizers:
          MyLambdaTokenAuthorizer:
            FunctionArn: !GetAtt MyAuthFunction.Arn

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: my_folder/
      Handler: hello.handler
      Runtime: python3.9
      Events:
        GetRoot:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get

  MyAuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: my_folder/
      Handler: authorizer.handler
      Runtime: python3.9

The problem I have is the api as it currently stands is open to anyone to use it, so I want to control access to the api so that someone must signup and login before using the api.

Reading tutorials online on how to create an authorizer I've found this:

  1. A client will make a request to the API.
  2. The API Gateway will determine if a custom authorizer is configured and will invoke it.
  3. The custom authorizer will then determine if the token is valid and generate a policy.
  4. The API Gateway will check the policy and will either “allow” or “deny” your request to the API.

Another part of this code I set up a cogito userpool/client. The user can signup, then once they successfully log-in this generates a JWT.

I currently dont have any code inside of my_folder/authorizer.handler. I also dont understand what the policy document is, I keep coming across the term but haven't seen it formally defined yet in terms of authorizations.

What I basically want to know is, when a user logs in and generates a JWT how do I verify it each time a user hits an api endpoint?

I imagine it would work like:

user logs in -> JWT generates -> client tries to access api endpoint (using Postman) -> "Unauthorized" is shown -> User uses the JWT for authorizer -> the authorizer intercepts this and verifies the user.

So every time a user goes to a different endpoint on my system the JWT is checked to verify the user is who they say they are.

I also want to confirm the user is in the cognito userpool. When I decoded the JWT using jwt.io it shows the user info such as username/password. Is there a way to add a second layer to authentication where the user info is checked against what is in the userpool?

0 Answers
Related