Affe
Affe

Reputation: 11

AWS SAM API gateway with CORS and DefaultAuthorizer is authorizing OPTIONS requests

I have an API gateway with CORS and a default authorizer, but obviously I don't want my options requests to be authorized. Luckily AWS made the attribute "AddDefaultAuthorizerToCorsPreflight" which when set to "false" should make sure that the default authorizer is not added to the generated options endpoints, the problem is that it doesn't seem to work... Here's a simplified version of my template:

Resources:
    myApiGateway:
        Type: AWS::Serverless::Api
        Properties:
            StageName: Staging
            Cors:
                AllowMethods: "'*'"
                AllowHeaders: "'*'"
                AllowOrigin: "'*'"
            Auth:
                Authorizers:
                    aadAuthorizer:
                        FunctionPayloadType: TOKEN
                        FunctionArn:
                            Fn::GetAtt:
                                - authorizerFunctionV1
                                - Arn
                DefaultAuthorizer: aadAuthorizer
                AddDefaultAuthorizerToCorsPreflight: false

I have fiddled a lot around with the template and tried to move some of the settings to Globals, but no matter what I do the result is the same.

The authorizer is applied to all my endpoints including the OPTIONS endpoints, so the browser gets a 401 when making preflight requests.

I have seen a lot of examples around 2019/2020 of people claiming that setting AddDefaultAuthorizerToCorsPreflight to false should work, but it doesn't. I'm starting to think that it's a regression.

Upvotes: 1

Views: 558

Answers (1)

Eric Cobos
Eric Cobos

Reputation: 1

I had the same problem, you should additionaly add AddApiKeyRequiredToCorsPreflight and set value to false, should look like this:

Resources:
myApiGateway:
    Type: AWS::Serverless::Api
    Properties:
        StageName: Staging
        Cors:
            AllowMethods: "'*'"
            AllowHeaders: "'*'"
            AllowOrigin: "'*'"
        Auth:
            Authorizers:
                aadAuthorizer:
                    FunctionPayloadType: TOKEN
                    FunctionArn:
                        Fn::GetAtt:
                            - authorizerFunctionV1
                            - Arn
            DefaultAuthorizer: aadAuthorizer
            AddDefaultAuthorizerToCorsPreflight: false
            AddApiKeyRequiredToCorsPreflight: false

Here you've the link with the docs: https://docs.aws.amazon.com/es_es/serverless-application-model/latest/developerguide/sam-property-api-apiauth.html

Upvotes: 0

Related Questions