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

如何在API Gateway自定义Lambda授权中配置含httpMethod的identitySource

API Gateway自定义Lambda授权:结合HTTP方法与Authorization头实现缓存的配置方案

核心配置:identitySource的正确格式

要同时将Authorization头和HTTP方法纳入缓存键,identitySource的正确字符串格式是:

method.request.header.Authorization,context.request.httpMethod

其中:

  • method.request.header.Authorization 是获取请求头中Authorization字段的标准表达式
  • context.request.httpMethod 是获取当前请求HTTP方法(GET/POST/PUT等)的正确路径,注意驼峰拼写(httpMethod不能写成HTTPMethod或其他形式)

Swagger配置示例

在你的Swagger/YAML文件中,对应自定义授权器的配置片段如下:

components:
  securitySchemes:
    CustomLambdaAuthorizer:
      type: apiKey
      name: Authorization
      in: header
      x-amazon-apigateway-authorizer:
        type: token  # 使用TOKEN类型授权,基于identitySource内容生成缓存键
        authorizerUri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:YourAuthorizerFunction/invocations
        authorizerResultTtlInSeconds: 300  # 缓存有效期,按需调整(单位:秒)
        identitySource: method.request.header.Authorization,context.request.httpMethod

paths:
  /your-api-endpoint:
    get:
      security:
        - CustomLambdaAuthorizer: []
      x-amazon-apigateway-integration:
        # 你的API集成配置(比如指向Lambda或HTTP后端)
        type: aws_proxy
        uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:YourBackendFunction/invocations
        httpMethod: POST

Lambda授权函数的处理逻辑

由于TOKEN类型授权会将identitySource中的多个值用逗号拼接成一个字符串传入Lambda的authorizationToken参数,你需要在函数中拆分这两个值:

def lambda_handler(event, context):
    # 拆分Authorization头和HTTP方法,只做一次拆分避免Authorization头含逗号的情况
    auth_header, http_method = event['authorizationToken'].split(',', 1)
    
    # 结合两个参数执行授权逻辑
    # 例如:验证token有效性,同时检查该token是否允许使用当前HTTP方法访问资源
    is_authorized = your_auth_logic(auth_header, http_method)
    
    if is_authorized:
        return {
            'principalId': 'user-123',
            'policyDocument': {
                'Version': '2012-10-17',
                'Statement': [
                    {
                        'Action': 'execute-api:Invoke',
                        'Effect': 'Allow',
                        'Resource': event['methodArn']
                    }
                ]
            }
        }
    else:
        raise Exception('Unauthorized')

控制台操作失败的常见原因

  1. 表达式拼写错误:确保context.request.httpMethod的大小写和路径正确,不要写成context.httpMethod或method.request.httpMethod
  2. 授权类型不匹配:如果选择REQUEST类型授权,缓存逻辑会基于整个请求而非指定的identitySource值,需切换为TOKEN类型
  3. 权限配置缺失:API Gateway未获得调用Lambda授权函数的权限,需在Lambda的资源策略中添加API Gateway的访问权限

内容的提问来源于stack exchange,提问作者Julian Dm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:13:18