Skip to content

CORS + Cognito Authorization #2136

@jhechtf

Description

@jhechtf

Description:

When using CORS with a Cognito Authorizer the generated OPTIONS requests also require cognito authorization. This was throwing errors when attempting to call the API endpoint from the browser as the authorization header is not passed along.

E.G. here is the pre-flight request made to the API Gateway endpoint.

image

Note: there is not an "authorization" header present.

Steps to reproduce:

  1. Create a new sam-based repo with the CLI. I use nodeJS for my lambda.
  2. Add the following code to the Resources section
ApiGateway:
  Type: AWS::Serverless::Api
  Properties:
    StageName: !Ref Stage
    Cors: "'*'"
    Auth:
      DefaultAuthorizer: MyCognitoAuthorizer
      Authorizers:
        MyCognitoAuthorizer:
          UserPoolArn: !ImportValue  UserPoolArn
# Each Lambda function is defined by properties:
# https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

# get all items.
GetTodosFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: src/handlers/get.getHandler
    Runtime: nodejs14.x
    MemorySize: 128
    Timeout: 100
    Description: A simple example includes a HTTP get method to get all items from a DynamoDB table.
    Policies:
      # Give Create/Read/Update/Delete Permissions to the SampleTable
      - DynamoDBCrudPolicy:
          TableName: !Ref TodosTable
    Environment:
      Variables:
        # Make table name accessible as environment variable from function code during execution
        TODOS_TABLE: !Ref TodosTable
        NODE_ENV: !If [isProd, 'production', 'development']
        REGION: !Ref AWS::Region
    Events:
      GetApi:
        Type: Api
        Properties:
          RestApiId: !Ref ApiGateway
          Path: /
          Method: GET

Observed result:

The mock method created for the OPTIONS request requires cognito authorization, which breaks the ability to call the API from any browser* (tested with Edge, Chrome, and Firefox).

Expected result:

Even if there is an authorizer present, OPTIONS requests should likely not have it added as it is likely to break browser functionality.

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

  1. OS: Windows 10
  2. If using SAM CLI, sam --version: 1.27.2
  3. AWS region: us-west-2

Add --debug flag to any SAM CLI commands you are running

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions