繁体   English   中英

谁能提供在 HttpApi 资源中设置了 CORS 的 AWS SAM 模板的工作示例?

[英]Can anyone provide a working example of an AWS SAM template that has CORS setup in a HttpApi resource?

我一直在四处走动,试图让它发挥作用。 我希望能够在HttpApi资源定义中定义CorsConfiguration ,但我尝试的一切都不起作用。 如果我全局定义它,我只能让 CORS 工作,但这只有在我没有定义 HttpApi 资源时才有效。

以下是我目前根据文档所做的。

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

其结果是 OPTIONS(预检)请求的 403。

请有人可以提供一个工作示例吗? 但是我在任何地方都找不到实际的工作示例,而且文档令人气愤!

帮助我 Stack Overflow,你是我唯一的希望!

  1. 您应该将POSTOPTIONS添加到AllowMethods
CorsConfiguration
  AllowMethods:
    - GET
    - POST
    - OPTIONS

这将涵盖预检请求需求。

  1. 请注意您的 HTTP API 资源类型定义中的拼写错误(必须是AWS::Serverless::HttpApi

这个文档有效。

这是我用来为我的 HttpApi 配置 CORS 的内容(注意:我将其与 Cognito 授权方一起使用):

    Resources:
      ApiGatewayApi:
        Type: AWS::Serverless::HttpApi
        Properties:
          StageName: Prod
          DefaultRouteSettings:
            ThrottlingBurstLimit: 5
            ThrottlingRateLimit: 20
          Auth:
            Authorizers:
              GeneralAuth:
                AuthorizationScopes:
                  - email
                IdentitySource: "$request.header.Authorization"
                JwtConfiguration:
                  issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPoolId}
                  audience:
                    - !Ref Audience
          CorsConfiguration:
            AllowMethods:
              - GET
            AllowOrigins:
              - http://localhost:8080

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM