首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >由于AWS Api网关中的CORS阻塞而拒绝访问

由于AWS Api网关中的CORS阻塞而拒绝访问
EN

Stack Overflow用户
提问于 2022-01-07 12:45:03
回答 1查看 229关注 0票数 1

我有一个AWS SAM模板,它在API网关中创建lambda函数和post方法。默认情况下,它使用Lambda代理集成,当我通过PostMan工具进行测试时,它工作得很好,但是当我在沙箱应用程序中使用API网关URL时,它显示了以下错误。

代码语言:javascript
运行
复制
Access to XMLHttpRequest at 'https://abcdef.execute-api.eu-west-2.amazonaws.com/dev/my-api' from origin 'https://abcd.csb.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

但是当我手动创建API网关post方法并尝试时,它就正常工作了。

Lambda函数还在响应中返回以下标题。

代码语言:javascript
运行
复制
response = {
        'statusCode': status_code,
        'headers': {
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,POST'
        },
        'body': json.dumps(response_data)
    }

以下是AWS SAM模板。

代码语言:javascript
运行
复制
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  AWS SAM Template

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 10

Parameters:
  DeploymentEnv:
    Type: String

Resources:
  ApiGatewayApi:
    DependsOn: LambdaFunction
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref DeploymentEnv
      EndpointConfiguration: 
        Type: REGIONAL
      Cors:
        AllowMethods: "'POST,OPTIONS'"
        AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
        AllowOrigin: "'*'"
        MaxAge: "'600'"
        AllowCredentials: false
      Auth:
        DefaultAuthorizer: NONE
        ApiKeyRequired: true # sets for all methods
  
  LambdaFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      FunctionName: !Join [ "", [ !Ref DeploymentEnv, "-my-lambda"]]
      CodeUri: my_api/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Events:
        EventTriggerlambda:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties: 
            RestApiId: !Ref ApiGatewayApi
            Path: /my-api
            Method: POST
            Auth:
              ApiKeyRequired: true
      Role: Role_URN
      Environment:
        Variables:
          URI: Test
          USER_NAME: Test
          PASSWORD: Test
  
  ApiKey:
    Type: AWS::ApiGateway::ApiKey
    DependsOn: ApiGatewayApiStage
    Properties:
      Name: !Join ["", [{"Ref": "AWS::StackName"}, "-apikey"]]
      Enabled: true
      StageKeys:
        - RestApiId: !Ref ApiGatewayApi
          StageName: !Ref DeploymentEnv
  
  UsagePlan:
    DependsOn: 
      - ApiGatewayApiStage
    Type: AWS::ApiGateway::UsagePlan
    Properties:
      ApiStages:
        - ApiId: !Ref ApiGatewayApi
          Stage: !Ref DeploymentEnv
      Throttle:
        BurstLimit: 500
        RateLimit: 100
      UsagePlanName: MY-UsagePlan
      
  UsagePlanKey:
    Type: AWS::ApiGateway::UsagePlanKey
    Properties:
      KeyId: !Ref ApiKey
      KeyType: API_KEY
      UsagePlanId: !Ref UsagePlan

Outputs:
  LambdaFunction:
    Description: "Lambda Function ARN"
    Value: !GetAtt LambdaFunction.Arn

请帮助,谢谢:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-11 17:16:25

配置不适合在AWS SAM模板中的API网关中创建API。由于SAM部署默认使用lambda代理集成,这就是为什么在方法响应中很少需要使用上述配置自动设置所需的值。因此,我使用open规范,其中定义了Rest配置,并且在部署后无需任何手动干预就可以正常工作。

下面的配置是可以的。

代码语言:javascript
运行
复制
ApiGatewayApi:
    DependsOn: LambdaFunction
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref DeploymentEnv
      DefinitionBody:
          'Fn::Transform':
            Name: 'AWS::Include'
            Parameters:
              Location: !Join [ '', [ 's3://mybucket', '/openapi-spec.yaml'  ] ]
      EndpointConfiguration: 
        Type: REGIONAL

OpenAPi配置

代码语言:javascript
运行
复制
openapi: "3.0.1"
info:
  title: "test-api"
  description: "Created by AWS Lambda"
  version: "2022-01-07T18:00:40Z"

paths:
  /test-api:
    post:
      responses:
        "200":
          description: "200 response"
          headers:
            Access-Control-Allow-Origin:
              schema:
                type: "string"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Empty"
      x-amazon-apigateway-integration:
        httpMethod: "POST"
        uri:  
          Fn::Sub: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations"
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Origin: "'*'"
        passthroughBehavior: "when_no_match"
        contentHandling: "CONVERT_TO_TEXT"
        type: "aws_proxy"
    options:
      responses:
        "200":
          description: "200 response"
          headers:
            Access-Control-Allow-Origin:
              schema:
                type: "string"
            Access-Control-Allow-Methods:
              schema:
                type: "string"
            Access-Control-Allow-Headers:
              schema:
                type: "string"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Empty"
      x-amazon-apigateway-integration:
        responses:
          default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
        requestTemplates:
          application/json: "{\"statusCode\": 200}"
        passthroughBehavior: "when_no_match"
        type: "mock"
    x-amazon-apigateway-any-method:
      responses:
        "200":
          description: "200 response"
          content: {}
      security:
      - api_key: []
      x-amazon-apigateway-integration:
        httpMethod: "POST"
        uri: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${LambdaFunction.Arn}/invocations"
        responses:
          ".*":
            statusCode: "200"
        passthroughBehavior: "when_no_match"
        type: "aws_proxy"
components:
  schemas:
    Empty:
      title: "Empty Schema"
      type: "object"
  securitySchemes:
    api_key:
      type: "apiKey"
      name: "x-api-key"
      in: "header"

在这里,openapi-spec.yaml文件保存在与AWS模板相同的文件夹中,并且在部署之前,它被上传到S3桶中,开始使用GitHub工作流管道文件中的以下命令。

代码语言:javascript
运行
复制
- run: aws s3 cp openapi-spec.yaml s3://mnai-code-deployments
        - run: sam build
        - run: sam deploy --no-confirm-changeset --no-fail-on-empty-changeset --stack-name my-stack --s3-bucket mybucket  --capabilities CAPABILITY_IAM --region eu-west-2 --parameter-overrides ParameterKey=DeploymentEnv,ParameterValue=dev ParameterKey=S3Bucket,ParameterValue=mybucket

谢谢

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70621463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档