You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS SAM的OpenAPI定义中移除OPTIONS方法的双重认证

解决AWS Serverless Api OPTIONS方法认证移除问题

问题分析

你遇到的核心问题是全局配置的API-Key认证会覆盖OPTIONS方法的局部security: - NONE: []配置,而移除全局配置后POST方法的安全规则没生效,是因为OpenAPI配置需要正确关联认证资源。

正确解决方案

方案1:保留全局配置,针对OPTIONS方法彻底关闭认证

在OpenAPI的OPTIONS方法定义中,不仅要指定security: - NONE: [],还要显式设置x-amazon-apigateway-api-key-required: false,同时清除该方法的x-amazon-apigateway-authorizer配置。示例片段:

paths:
  /your-endpoint:
    options:
      summary: CORS preflight
      x-amazon-apigateway-api-key-required: false
      x-amazon-apigateway-authorizer:
        type: NONE
      security:
        - NONE: []
      responses:
        200:
          description: OK
          headers:
            Access-Control-Allow-Origin:
              type: string
            Access-Control-Allow-Methods:
              type: string
            Access-Control-Allow-Headers:
              type: string

方案2:移除全局配置,确保POST方法安全配置生效

  • 先在AWS::Serverless::Api资源中移除DefaultAuthorizer和ApiKeyRequired的全局设置。
  • 在OpenAPI的POST方法里,同时配置TokenAuthorizer和API-Key的安全规则,并且要确保认证资源(Authorizer和ApiKey)已经在Serverless模板中定义。示例片段:
# Serverless模板中的Api资源
Resources:
  YourApi:
    Type: AWS::Serverless::Api
    Properties:
      DefinitionBody:
        openapi: 3.0.1
        info:
          title: Your API
          version: 1.0.0
        components:
          securitySchemes:
            TokenAuthorizer:
              type: apiKey
              name: Authorization
              in: header
              x-amazon-apigateway-authtype: custom
              x-amazon-apigateway-authorizer:
                type: token
                authorizerUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${YourAuthorizerLambda.Arn}/invocations
                identitySource: method.request.header.Authorization
            ApiKeyAuth:
              type: apiKey
              name: x-api-key
              in: header
        paths:
          /your-endpoint:
            post:
              security:
                - TokenAuthorizer: []
                - ApiKeyAuth: []
              x-amazon-apigateway-integration:
                type: aws_proxy
                uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${YourPostLambda.Arn}/invocations
                httpMethod: POST
              responses: {}

关键注意点

  • API-Key认证优先级:全局ApiKeyRequired会覆盖方法级的设置,所以必须在OPTIONS方法显式关闭x-amazon-apigateway-api-key-required。
  • 安全规则关联:在components/securitySchemes中必须正确定义TokenAuthorizer和ApiKeyAuth,POST方法的security数组才能正确关联这些认证方式。

内容的提问来源于stack exchange,提问作者Bhavesh Achhada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:50:45