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

AWS RestAPI未将Cognito认证信息转发至Lambda函数

解决API Gateway未将授权用户信息转发至Lambda的问题

以下是针对你遇到的问题的具体排查和解决步骤:

  • 先确认信息存放位置:别找错地方
    如果你的API Gateway用的是Lambda代理集成(这是CDK中LambdaIntegration的默认配置),授权用户信息不会出现在context.identity里,而是在event.requestContext.authorizer对象中。很多人会误查context.identity,先打印整个event对象查看CloudWatch日志,确认这一点。

  • 检查CDK中的集成与授权器配置
    确保API方法正确关联了授权器,并且配置了必要的信息传递逻辑:

    1. 关联授权器时,明确指定authorizationType和对应的授权器实例:
      const getMethod = myResource.addMethod('GET', new apigateway.LambdaIntegration(myLambda), {
        authorizer: customAuthorizer,
        authorizationType: apigateway.AuthorizationType.CUSTOM,
      });
      
    2. 若使用非代理集成(proxy: false),必须手动添加集成请求映射模板,将授权上下文映射到Lambda输入:
      比如在CDK中为集成添加映射:
      const integration = new apigateway.LambdaIntegration(myLambda, {
        proxy: false,
        requestTemplates: {
          'application/json': JSON.stringify({
            principalId: '$context.authorizer.principalId',
            userContext: '$context.authorizer'
          })
        }
      });
      
  • 验证自定义授权器的返回格式
    自定义授权器必须返回符合AWS规范的JSON结构,其中context字段会被转发到API Gateway:

    {
      "principalId": "your-user-id",
      "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [{
          "Action": "execute-api:Invoke",
          "Effect": "Allow",
          "Resource": "your-api-resource-arn"
        }]
      },
      "context": {
        "username": "test-user",
        "email": "test@example.com"
      }
    }
    

    这个context中的内容会出现在Lambda的event.requestContext.authorizer(代理集成)或你指定的映射字段中(非代理集成)。

  • 打印完整输入排查
    在Lambda中打印整个event和context,通过CloudWatch日志确认数据流向:
    Node.js示例:

    exports.handler = async (event) => {
      console.log('Full Event:', JSON.stringify(event, null, 2));
      return { statusCode: 200 };
    };
    

    Rust示例(使用aws-lambda-runtime):

    use aws_lambda_events::apigw::ApiGatewayProxyRequest;
    use lambda_runtime::{run, service_fn, Error, LambdaEvent};
    
    async fn handler(event: LambdaEvent<ApiGatewayProxyRequest>) -> Result<(), Error> {
        println!("Full Event: {:?}", event.payload);
        Ok(())
    }
    
    #[tokio::main]
    async fn main() -> Result<(), Error> {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::INFO)
            .with_target(false)
            .without_time()
            .init();
    
        run(service_fn(handler)).await
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:25:46