Search code examples
aws-serverlessaws-sam

AWS SAM template for serverless::api not creating cognito user pool authorizer


I can't figure out why after deploying this template I don't see any Authorizer for this API under the "Authorizers" tab on AWS console.

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

Globals:
  Function:
    Timeout: 3

Resources:
 
  ProductGet:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: ./
      Handler: product-get.lambda_handler
      Runtime: python3.8
      Role: "particular role here"
      Events:
        ProductGet:
          Type: Api 
          Properties:
            Path: /product-get
            Method: post
            Auth:
              Authorizers:
                MyCognitoAuth:
                 UserPoolArn: "user pool arn here"
                 AuthType: "COGNITO_USER_POOLS"
              DefaultAuthorizer: MyCognitoAuth

Solution

  • Figured out it. You cannot define authorizers in "Events" section. If your API needs an authorizer, you'll have to define that API as a separate resource and link it to the events using APIid.

    Sample code below.

    MyApi:
        Type: AWS::Serverless::Api
        Properties:
          StageName: Prod
          Auth:
            DefaultAuthorizer: MyCognitoAuth # OPTIONAL
            Authorizers:
              MyCognitoAuth:
                Type: COGNITO_USER_POOLS
                # Can also accept an array
                UserPoolArn: "user pool arn here"
    
      ProductGet:
        Type: AWS::Serverless::Function         
        Properties:
          CodeUri: ./
          Handler: product-get.lambda_handler
          Runtime: python3.8
          Role: 'role ARN here'
          Events:
            ProductGet:
              Type: Api 
              Properties:
                Path: /product-get
                Method: post
                RestApiId: !Ref MyApi #This is how you need to refer to your API
                Auth:
                  Authorizer: MyCognitoAuth