使用AWS::ApiGateway::Authorizer时Lambda无法获取授权上下文
请求型API Gateway授权器上下文无法传递到后端Lambda的问题解决
问题描述
配置基于AWS SAM的请求型API Gateway授权器后,授权验证成功,但后端Lambda无法通过event.get("requestContext", {}).get("authorizer", {}).get("custom_key", None)获取授权器返回的上下文数据。相关配置如下:
SAM模板配置
ApiGatewayAuthorizer: Type: AWS::ApiGateway::Authorizer Properties: AuthorizerResultTtlInSeconds: 0 AuthorizerUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${APIGatewayAuthFunction.Arn}/invocations IdentitySource: method.request.header.Authorization Name: ApiGatewayAuthorizer RestApiId: !Ref ApiWithAuthorizer Type: REQUEST # this is API with authorizer ApiWithAuthorizer: Type: AWS::Serverless::Api Properties: StageName: Dev EndpointConfiguration: Type: REGIONAL Auth: DefaultAuthorizer: ApiGatewayAuthorizer ApiGatewayAuthorizerInvokePermission: Type: AWS::Lambda::Permission Properties: FunctionName: !GetAtt APIGatewayAuthFunction.Arn Action: lambda:InvokeFunction Principal: apigateway.amazonaws.com APIGatewayAuthFunction: Type: AWS::Serverless::Function Properties: Timeout: 600 CodeUri: authorizer/ Handler: app.lambda_handler Runtime: python3.11 FunctionName: APIGatewayAuthFunction MyAPILambdaFunction: Type: AWS::Serverless::Function Properties: Timeout: 600 CodeUri: hello/ Handler: app.lambda_handler Runtime: python3.11 FunctionName: MyAPILambdaFunction Role: !GetAtt ApiGatewayLambdaExecutionRole.Arn Layers: - !Ref MyApiSharedLayer Events: InventoryListApi: Type: Api Properties: RestApiId: !Ref ApiWithAuthorizer Path: /hello Method: get
授权器返回响应
{ "principalId": "yyyyy", "policyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "ARN of the method", } ], }, "context": {"custom_key": "custom_value"}, }
解决方案
1. 完善SAM API的授权器关联配置
手动创建AWS::ApiGateway::Authorizer后,仅通过DefaultAuthorizer引用不足以让SAM启用上下文传递逻辑,需在API的Auth配置中显式声明授权器的类型与属性:
修改ApiWithAuthorizer的配置,添加Authorizers节点:
ApiWithAuthorizer: Type: AWS::Serverless::Api Properties: StageName: Dev EndpointConfiguration: Type: REGIONAL Auth: DefaultAuthorizer: ApiGatewayAuthorizer Authorizers: ApiGatewayAuthorizer: Type: REQUEST IdentitySource: method.request.header.Authorization FunctionArn: !GetAtt APIGatewayAuthFunction.Arn
2. 修复授权器响应的JSON格式错误
返回的JSON中存在多余尾逗号(如"Resource": "ARN of the method",和"context": {"custom_key": "custom_value"},后的逗号),会导致API Gateway解析异常,无法正确传递上下文。修正后的响应如下:
{ "principalId": "yyyyy", "policyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "ARN of the method" } ] }, "context": {"custom_key": "custom_value"} }
3. 验证授权器的API关联配置
确认ApiGatewayAuthorizer中的RestApiId正确引用ApiWithAuthorizer,这是授权器与目标API绑定的核心配置,引用错误会导致授权器无法正常作用。
完成以上修改后重新部署SAM应用,后端Lambda即可正常获取授权器传递的上下文数据。
内容的提问来源于stack exchange,提问作者Pritam Kadam
相关产品推荐
相关产品推荐

