I have been going round and round trying to get this working. I want to be able to define the CorsConfiguration
in the HttpApi resource definition but everything I try simply doesn’t work. I can only get CORS working if I defined it globally, but that only works if I don’t define the HttpApi resource.
The following is what i have so far based on the documentation.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
Globals:
Function:
Timeout: 3
Resources:
MainApi:
Type: AWS::Serverless:HttpApi
Properties:
CorsConfiguration:
AllowHeaders:
- "*"
AllowMethods:
- "GET"
AllowOrigins:
- "http://localhost:8000"
ExposeHeaders:
- "*"
DefinitionBody:
openapi: 3.0.1
info:
title: !Ref 'AWS::StackName'
paths: {}
CheckHumanFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
Architectures:
- x86_64
Events:
CheckHuman:
Type: HttpApi
Properties:
ApiId: !Ref MainApi
Path: /human-check
Method: post
Metadata:
DockerTag: nodejs16.x-v1
DockerContext: ./api/human-check
Dockerfile: Dockerfile
Outputs:
MainApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
CheckHumanFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt CheckHumanFunction.Arn
CheckHumanFunctionIamRole:
Description: "Implicit IAM Role created for CheckHuman function"
Value: !GetAtt CheckHumanFunctionIamRole.Arn
The result of this is a 403 on the OPTIONS (preflight) request.
Please can someone provide a working example? But I cannot find an actual working example anywhere and the documentation is infuriating!
Help me Stack Overflow, you’re my only hope!
2
Answers
POST
andOPTIONS
to AllowMethods:This will cover the preflight request needs.
AWS::Serverless::HttpApi
)This docs works.
Here is what I am using to configure CORS for my HttpApi (note: I’m using this with a Cognito Authorizer):