How to enable CORS with AWS SAM

Jan*_*Jan 16 amazon-web-services cors aws-api-gateway aws-sam infrastructure-as-code

I'm trying to enable CORS in my AWS SAM app. Here is the snippet from my template.yaml:

Globals:
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Auth:
        Authorizers:
          MyCognitoAuthorizer: ...

  getByIdFunc:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.handle
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /{id}
            Method: GET
            RestApiId: !Ref MyApi
Run Code Online (Sandbox Code Playgroud)

根据此Using CORS with AWS SAMhttps://github.com/aws/serverless-application-model/issues/373,cors配置应该可以工作,但不幸的是API响应上没有设置标头,如下所示。

< HTTP/2 200 
< content-type: application/json
< content-length: 770
< date: Tue, 13 Apr 2021 19:55:31 GMT
< x-amzn-requestid: ...
< x-amz-apigw-id: ...
< x-amzn-trace-id: Root=1-...-...;Sampled=0
< x-cache: Miss from cloudfront
< via: 1.1 ...cloudfront.net (CloudFront)
< x-amz-cf-pop: FRA2-C2
< x-amz-cf-id: ...==
< 
* Connection #0 to host ....execute-api.eu-central-1.amazonaws.com left intact
[{"model": ..}]
Run Code Online (Sandbox Code Playgroud)

我还尝试将 cors 配置添加到 API 定义 (MyApi) 本身,就像官方文档中所述,但没有成功。

我可以自己在响应中添加标头,但我宁愿将其放在模板文件中。

isa*_*123 21

为我解决这个问题的方法是将以下内容添加到我的 template.yaml 中:

Globals:
    Api:
        Cors:
            AllowMethods: "'GET,POST,OPTIONS'"
            AllowHeaders: "'content-type'"
            AllowOrigin: "'*'"
            # AllowCredentials: true  Uncomment only if you choose a specific origin instead of the * wildcard.
Run Code Online (Sandbox Code Playgroud)

正如 nirvana124 和 Nitesh 所说,您还需要在每个端点中返回这些标头和响应:

return {
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Headers" : "Content-Type",
        "Access-Control-Allow-Origin": "*", // Allow from anywhere 
        "Access-Control-Allow-Methods": "GET" // Allow only GET request 
    },
    body: JSON.stringify(response)
}
Run Code Online (Sandbox Code Playgroud)


小智 9

使用 SAM/CloudFormation 或 AWS 控制台,您可以为 OPTIONS 方法设置 CORS 标头,该方法将在调用实际 API 方法(GET/POST 等)之前由浏览器调用。邮递员或任何其他服务只会调用您的端点。

当我们将lambda 代理与 API Gateway结合使用时,我们需要在 lambda 的响应对象中设置 CORS 标头。

要为 Lambda 代理集成启用 CORS,您必须将 Access-Control-Allow-Origin: 添加domain-name到输出标头。域名可以是*任何域名。

return {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*", // Allow from anywhere 
            "Access-Control-Allow-Methods": "GET" // Allow only GET request 
        },
        body: JSON.stringify(response)
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

对于使用 API Gateway 版本 2 ( HttpApi ) 的任何人来说,它不支持“AddDefaultAuthorizerToCorsPreflight”,至少在其文档中没有指定。

相反(根据 AWS指南),我们需要在 OPTIONS /{proxy+} 的 lambda 函数中添加一条路由,并关闭该路由的身份验证。

MyHttpApi:
 Type: AWS::Serverless::HttpApi
 Properties:
  Auth:
    DefaultAuthorizer: OAuth2
    Authorizers:
      OAuth2:
        JwtConfiguration:
          issuer: "..."
          audience:
            - ...
        IdentitySource: "$request.header.Authorization"
  CorsConfiguration:
    AllowOrigins:
      - "*"
    AllowMethods: 
      - GET
      - POST
      - OPTIONS
    AllowHeaders:
      - Content-Type
      - Accept
      - Access-Control-Allow-Headers
      - Access-Control-Request-Method
      - Access-Control-Request-Headers
      - Authorization
MyLambdaFunction:
 Type: AWS::Serverless::Function
 Properties:
  Handler: index.handler
  Events:
    CorsPreflightEvent:
      Type: HttpApi
      Properties:
        Path: /{proxy+}
        Method: OPTIONS
        Auth:
          Authorizer: NONE
        ApiId: !Ref MyHttpApi
Run Code Online (Sandbox Code Playgroud)