GeekOnGadgets
GeekOnGadgets

Reputation: 959

API Gateway Options method throwing 403

I have a Custom Authorizer with API Gateway. When deployed through SAM Module it also creates Options Method when you enable CORS. The thing I really don't understand is why the custom authorizer gets attached to Options endpoint? enter image description here

This is throwing 403 when I try to call the endpoint from browser and works perfectly fine when I remove Authorization from the Options method.

enter image description here

Below is the template.yaml

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

Globals:
  Function:
    Runtime: nodejs8.10
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

Resources:
  TestApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Auth:
        DefaultAuthorizer: testAuthoriser
        Authorizers:
          testAuthoriser:
            FunctionArn:
              Fn::ImportValue: !Sub test-custom-autoriser
            Identity:
              Header: Authorization
              ValidationExpression: ^Bearer [-0-9a-zA-Z\._]*$
              ReauthorizeEvery: 30 

  Version:
    Type: 'AWS::Serverless::Function'
    Properties:
      FunctionName: test
      CodeUri: src/test
      Handler: index.test
      Events:
        EndPoint:
          Type: Api
          Properties:
            RestApiId: !Ref TestApi
            Path: /test
            Method: get
            Auth:
              Authorizer: testAuthoriser

I have enabled the 'Access-Control-Allow-Origin': '*' in header as well. Not sure what's going on here. Any help would be appreciated

Upvotes: 6

Views: 8485

Answers (2)

youjin
youjin

Reputation: 2579

Here's the answer, see the aws sam issue here

 Api:
    Cors:
      AllowHeaders: "'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization'" 
      AllowOrigin: "'*'"
    Auth:
      DefaultAuthorizer: CognitoAuthorizer
      Authorizers:
        CognitoAuthorizer:
          UserPoolArn: yourUserPool
      AddDefaultAuthorizerToCorsPreflight: False // <== this line

Upvotes: 6

A.Khan
A.Khan

Reputation: 4002

For CORS, AWS API Gateway will always enable OPTIONS method to allow preflight test. You can read more on that in the docs.

The reason you are seeing preflight error in your browser because 403 Forbidden is coming from your Custom Authorizer. Custom Authorizer do not return headers so you will always see preflight error if request is rejected by Custom Authorzer.

To debug this, log the Policy your Custom Authorizer is returning. You can then see that in CloudWatch. Policy must contain Allow statement for the Resource being requested.

Upvotes: 0

Related Questions