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

如何让单个AWS API端点同时支持Lambda与AWS_IAM授权?

同一个API端点支持Lambda和AWS IAM双授权的可行方案

方案1:使用API Gateway多重授权功能

AWS API Gateway原生支持为单个方法配置多个授权器,按顺序验证请求,只要其中一个授权通过就允许访问。

SAM模板配置示例

调整你的SAM定义,为目标API方法同时绑定Lambda授权器和IAM授权器:

MyApi:
  Type: AWS::Serverless::Api
  Properties:
    Name: MyApi
    StageName: dev
    Auth:
      Authorizers:
        # 定义Lambda授权器
        LambdaAuth:
          FunctionArn: !GetAtt YourLambdaAuthorizer.Arn
          IdentitySource: method.request.header.Authorization
        # 定义IAM授权器
        IamAuth:
          Type: AWS_IAM

SampleEvent:
  Type: AWS::Serverless::Function
  Properties:
    Handler: index.handler
    Runtime: python3.12
    Events:
      SampleApi:
        Type: Api
        Properties:
          RestApiId: !Ref MyApi
          Path: /api/sample
          Method: POST
          Auth:
            Authorizer: ALL
            Authorizers:
              - LambdaAuth
              - IamAuth

授权逻辑:请求到达后,API Gateway优先用Lambda授权器验证,失败则自动尝试IAM授权,任一验证通过即可放行。

方案2:创建同后端的双路径别名

为同一个后端函数创建两个不同的API路径,分别配置对应授权方式,再告知不同利益相关方使用各自的路径:

MyApi:
  Type: AWS::Serverless::Api
  Properties:
    Name: MyApi
    StageName: dev
    Auth:
      Authorizers:
        LambdaAuth:
          FunctionArn: !GetAtt YourLambdaAuthorizer.Arn
          IdentitySource: method.request.header.Authorization

# 给利益相关方1的Lambda授权路径
SampleEventLambda:
  Type: AWS::Serverless::Function
  Properties:
    Handler: index.handler
    Runtime: python3.12
    Events:
      LambdaAuthApi:
        Type: Api
        Properties:
          RestApiId: !Ref MyApi
          Path: /api/sample/lambda
          Method: POST
          Auth:
            Authorizer: LambdaAuth

# 给利益相关方2的IAM授权路径
SampleEventIam:
  Type: AWS::Serverless::Function
  Properties:
    Handler: index.handler
    Runtime: python3.12
    Events:
      IamAuthApi:
        Type: Api
        Properties:
          RestApiId: !Ref MyApi
          Path: /api/sample/iam
          Method: POST
          Auth:
            Authorizer: AWS_IAM

这种方案逻辑清晰,避免授权顺序冲突,但需要维护两个路径配置。

方案3:改造Lambda授权器兼容IAM验证

自定义Lambda授权器的逻辑,让它同时支持两种授权验证:

  • 当请求携带Authorization头部时,执行原有Lambda令牌验证逻辑
  • 当请求携带IAM签名相关头部(如X-Amz-Signature)时,调用AWS签名验证逻辑校验IAM身份

这种方案无需修改API Gateway配置,但需要额外开发IAM签名验证的代码,维护成本相对较高。

内容的提问来源于stack exchange,提问作者Akhil Prajapati

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 12:20:07