首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用OpenAPI为AWS API网关配置CORS?

如何使用OpenAPI为AWS API网关配置CORS?
EN

Stack Overflow用户
提问于 2020-07-04 23:00:15
回答 1查看 2.4K关注 0票数 0

我有一个应用编程接口的OpenAPI规范,我通过CDK部署它。该规范如下所示:

代码语言:javascript
运行
复制
openapi: 3.0.1
info:
  title: My API
  description: My REST API with CORS enabled
  version: 0.1.0

x-amazon-apigateway-cors:
  allowOrigins:
    - "*"
  allowCredentials: true
  exposeHeaders:
    - "x-apigateway-header"
    - "x-amz-date"
    - "content-type"
  maxAge: 3600
  allowMethods:
    - "*"
  allowHeaders":
    - "x-apigateway-header"
    - "x-amz-date"
    - "content-type"
    - "Authorization"

components:
  securitySchemes:
    lambda:
      type: "apiKey"
      name: "Authorization"
      in: "header"
      x-amazon-apigateway-authtype: "custom"
      x-amazon-apigateway-authorizer:
        authorizerUri: "{{my-lambda-authorizer}}"
        authorizerResultTtlInSeconds: 300
        type: "token" 

paths:
  /user/{id}:
    get:
      summary: Get info of specified user.
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: string
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
      security:
        - lambda: []
      x-amazon-apigateway-integration:
        uri: "{{my-lambda}}"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        type: "aws_proxy"

当我试图通过fetch()访问它时,我得到了一个错误的Failed to load resource: Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin

代码语言:javascript
运行
复制
fetch('https://api.example.com/user/1')
        .then(response => response.json())
        .then((user: User) => {
            // do something
        })
        .catch((err) => {
            console.log("Error: " + err);
        });

这个应用程序接口可以在api.example.com上访问,我在localhost:8000上使用Gatsby在本地运行该网站。

当我将x-amazon-apigateway-cors放在规范的根目录时,AWS docs似乎声明CORS是启用的,但是当我试图访问该API时,CORS似乎没有启用(或工作)。如何为我的API开启CORS,而不需要在控制台进行配置?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-05 01:10:04

Amazon API Gateway提供两种类型的API: REST API和HTTP API。REST API是最初随Amazon API Gateway引入的API,而HTTP APIs got announced at the end of 2019

根据对您的OpenAPI规范的描述,我假设您正在尝试部署REST API。然而,HTTP扩展只适用于x-amazon-apigateway-cors OpenAPI。

您现在有两个选择:要么切换到使用HTTP API,要么手动配置CORS。只要你不需要features only supported by REST APIs,我建议你改用HTTP API,因为这是Amazon API Gateway提供的更现代的API。

如果您想使用REST API,启用CORS需要更多的手动配置。亚马逊网络服务在Enabling CORS for a REST API resource中记录了这一点。本质上,你必须确保你的集成返回正确的CORS头。对于NodeJS AWS Lambda函数,可能如下所示:

代码语言:javascript
运行
复制
exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "https://www.example.com",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

对于CORS运行前请求,您还必须确保OPTIONS-request也返回正确的头。要实现这一点,最简单的方法是在OpenAPI规范中为OPTIONS-request添加一个模拟集成。这看起来像是:

代码语言:javascript
运行
复制
options:
  responses:
    '200':
      description: Default response
      headers:
        Access-Control-Allow-Headers:
          schema:
            type: string
        Access-Control-Allow-Methods:
          schema:
            type: string
        Access-Control-Allow-Origin:
          schema:
            type: string
  x-amazon-apigateway-integration:
    type: mock
    requestTemplates:
      application/json: |
        {"statusCode" : 200}
    responses:
      default:
        statusCode: 200
        responseParameters:
          method.response.header.Access-Control-Allow-Headers: "'*'"
          method.response.header.Access-Control-Allow-Methods: "'OPTIONS,POST'"
          method.response.header.Access-Control-Allow-Origin: "'https://example.com/'"

还请记住modern browsers don't support localhost as origin for CORS,所以你可能也需要解决这个问题。

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

https://stackoverflow.com/questions/62730683

复制
相关文章

相似问题

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