使用Terraform+OpenAPI配置AWS API Gateway时CORS未生效问题
问题解决:Terraform+OpenAPI配置AWS HTTP API Gateway CORS失效
问题背景
使用Terraform结合AWS Provider创建HTTP类型的API Gateway,通过OpenAPI配置接口逻辑,其他功能正常,但CORS设置未生效:前端发送OPTIONS预飞行请求时返回404 Not Found;手动在AWS控制台开启CORS后请求正常,但每次执行terraform apply会覆盖手动配置。期望通过OpenAPI的x-amazon-apigateway-cors字段自动生效CORS配置。
问题根源
- 全局启用了Cognito JWT认证(
security: [cognito-jwt: []]),导致自动生成的OPTIONS请求被要求携带Authorization头,预飞行请求因无认证信息被拦截或无法匹配路由。 - OpenAPI中未显式定义OPTIONS路由,API Gateway无法正确生成符合要求的预飞行响应。
修改OpenAPI文件的具体步骤
1. 为目标路径显式添加OPTIONS路由
在paths下的/requisitions节点中添加OPTIONS方法,使用MOCK集成直接返回CORS响应,无需转发到Lambda:
paths: '/requisitions': post: # 保留原POST方法的所有配置 options: summary: CORS预飞行请求处理 security: [] # 关闭该路由的Cognito认证 responses: '200': description: CORS预飞行响应 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: type: object x-amazon-apigateway-integration: type: MOCK requestTemplates: application/json: | { "statusCode": 200 } responses: default: statusCode: 200 responseParameters: method.response.header.Access-Control-Allow-Origin: "'*'" method.response.header.Access-Control-Allow-Methods: "'GET,OPTIONS,POST'" method.response.header.Access-Control-Allow-Headers: "'x-amzm-header,x-apigateway-header,x-api-key,authorization,x-amz-date,content-type'" responseTemplates: application/json: | {}
2. 优化全局CORS配置(可选)
保留全局x-amazon-apigateway-cors配置以确保接口一致性,可补充exposeHeaders和maxAge字段增强CORS功能:
x-amazon-apigateway-cors: allowOrigins: - '*' allowMethods: - GET - OPTIONS - POST allowHeaders: - x-amzm-header - x-apigateway-header - x-api-key - authorization - x-amz-date - content-type exposeHeaders: - Content-Length - X-Request-Id maxAge: 3600
验证部署
修改完成后执行terraform apply,API Gateway会自动创建正确的OPTIONS路由并配置CORS响应,前端预飞行请求将返回200,后续POST请求可正常执行,无需再手动在控制台修改CORS配置。
内容的提问来源于stack exchange,提问作者Spyros Argalias
相关产品推荐
相关产品推荐

