导入DRF Swagger JSON至AWS API Gateway时安全定义报错求助
问题原因及解决方案
核心问题:AWS API Gateway对API Key认证有强制规则
AWS API Gateway只识别**x-api-key**这个固定Header名称作为API Key的传递载体,你之前配置里用Authentication或Authorization作为Header名称,完全不符合AWS的要求,这是报错的根本原因。
另外,你后来把安全方案命名为Bearer却仍用apiKey类型是概念混淆:Bearer通常对应JWT认证,应该使用http类型的安全方案(指定scheme: bearer),而非apiKey类型。
正确配置示例
情况1:使用AWS API Key认证(对应初始需求)
修改securitySchemes中的Header名称为x-api-key,确保安全方案引用匹配:
openapi: 3.0.1 info: title: Backend API description: Api documentation version: 1.0.0 servers: - url: "xyz.com" paths: /xyz/{id}/: get: tags: - api description: "" operationId: api_xyz_read parameters: - name: id in: path required: true schema: type: string responses: '200': description: '' content: application/json: schema: $ref: '#/components/schemas/xyz' security: - ApiKeyAuth: [] # 名称可自定义,需与securitySchemes中的键一致 components: schemas: xyz: {} # 你的Schema定义 securitySchemes: ApiKeyAuth: # 自定义安全方案名称,可任意命名 type: apiKey name: x-api-key # 必须是这个值,AWS才会识别 in: header
情况2:如果实际使用Bearer Token(JWT)认证
若后端实际用JWT而非AWS API Key,需将安全方案类型改为http:
components: securitySchemes: BearerAuth: type: http scheme: bearer bearerFormat: JWT # 可选,说明是JWT类型 # 在操作或根级引用 security: - BearerAuth: []
额外注意事项
- 导入配置后,需在AWS API Gateway控制台的API设置中启用API Key验证,并将API与对应的使用计划关联,否则即使配置正确,API也不会验证API Key。
- 需根据后端实际认证机制选择对应安全方案类型,不要混淆API Key和Bearer Token两种认证逻辑。
内容的提问来源于stack exchange,提问作者Ravish Mallya
相关产品推荐
相关产品推荐

