Error on setting CORS header for API Gateway lambda authorizer
Asked Answered
L

1

6

I have a lambda authorizer for my API Gateway authorization. When authorizer returns 401 or 403 I do not get CORS back in response header. I am using AWS::Serverless::Api resource, and after some research found here that I need to set GatewayResponses to return custom headers for 4XX responses.

My Api Gateway definition looks like:

resApiGateway:
Type: AWS::Serverless::Api
Properties:
  StageName: !Sub "${env}"
  EndpointConfiguration: !If [IsLocal, "REGIONAL", "EDGE"]
  Cors:
    AllowMethods: "'OPTIONS,GET,POST,PUT,DELETE'"
    AllowHeaders: "'Content-Type,X-Amz-Date,Authorization'"
    AllowOrigin: "'*'"
  GatewayResponses:
    DEFAULT_4XX:
      ResponseParameters:
        "gatewayresponse.header.Access-Control-Allow-Origin": "'*'"
  ...
  ...

But I am getting error on cfn stack deployment:

Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [resApiGateway] is invalid. Invalid gateway response parameter 'gatewayresponse.header.Access-Control-Allow-Origin'
Lilylilyan answered 14/5, 2020 at 5:35 Comment(2)
Have you tried this syntax? (With Headers: under ResponseParameters)Pinhead
Awesome, it worked! Thank you @MikePatrick. Please put it in answers so I can accept.Lilylilyan
P
16

This feature was released with SAM v1.11.0. The release notes have a link to this sample application template, which demonstrates the feature.

Unfortunately, Amazon's own SAM documentation (which you linked to) only points you toward their OpenAPI extension docs.

These docs seem to show how you would configure API Gateway to use this feature with an OpenAPI specification, rather than with a SAM template.


To specify GatewayResponses in your SAM template, use the syntax found in the sample application:

Resources:
  restApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      GatewayResponses:
        DEFAULT_4XX:
          ResponseParameters:
            Headers:
              Access-Control-Allow-Origin: "'*'"
Pinhead answered 23/5, 2020 at 0:4 Comment(3)
Can't thank you enough for this! I have been searching for this for hours!! The linked sample application code is also 404 now. I ended up there from release notes but hit a dead end because of 404 until I saw your response here with an example yml snippet.Nosography
I'm still receiving an error when this is configured: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. Is there a way to fix this?Consumer
On Angular I was receiving 0 as status code and with this it solved my issue. Cheers mate!Bicameral

© 2022 - 2024 — McMap. All rights reserved.