Request Lambda Authorizer未触发问题求助
我配置了一个Request类型的Lambda Authorizer,但向创建的连接发起HTTP POST请求时,该Authorizer未被调用,且仍提示需附加Authorization信息。
我的代码实现
const customAuthorizer = createAuthorizer(scope, "ConnectionsAuth", { apiId: httpApi.attrApiId, name: "connectionsauth", authorizerType: "REQUEST", authorizerUri: `arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/${props.authorizerArn}/invocations`, authorizerResultTtlInSeconds: 120, identitySource: ["$request.header.Authorization"], authorizerPayloadFormatVersion: "2.0" }); export const createAuthorizer = (scope: Construct, id: string, props: CfnAuthorizerProps) => { return new apigateway.CfnAuthorizer(scope, id, props); }; export declare class CfnAuthorizer extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. */ static readonly CFN_RESOURCE_TYPE_NAME: string; /** * Build a CfnAuthorizer from CloudFormation properties * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. */ }
排查与解决方案
1. 关联Authorizer到具体路由
仅创建Authorizer资源是不够的,必须将其绑定到目标API路由,否则API Gateway不会触发该Authorizer。在CDK中需通过路由配置指定关联关系:
new apigateway.CfnRoute(scope, "ConnectionsRoute", { apiId: httpApi.attrApiId, routeKey: "POST /connections", target: `integrations/${yourIntegration.ref}`, authorizerId: customAuthorizer.ref, // 关键:绑定Authorizer到路由 authorizationType: "CUSTOM" // 指定使用自定义授权器 });
2. 确认AuthorizationType配置
确保路由的authorizationType设置为CUSTOM,而非默认的NONE或AWS_IAM,否则API Gateway不会启用自定义Authorizer。
3. 验证Lambda调用权限
确认API Gateway拥有调用Authorizer Lambda的权限。若手动指定Lambda ARN,需手动添加权限:
new lambda.CfnPermission(scope, "ApiGatewayInvokeAuthorizer", { action: "lambda:InvokeFunction", functionName: props.authorizerArn, principal: "apigateway.amazonaws.com", sourceArn: `arn:aws:execute-api:eu-west-1:${yourAccountId}:${httpApi.attrApiId}/*/*/*` });
4. 检查IdentitySource格式
部分CDK版本对identitySource的格式要求为字符串而非数组,可尝试修改为:
identitySource: "$request.header.Authorization"
5. 适配Payload格式版本
你使用了authorizerPayloadFormatVersion: "2.0",需确保Lambda Authorizer代码返回V2格式的响应:
export const handler = async (event) => { return { isAuthorized: true, context: { userId: "123" } }; };
内容的提问来源于stack exchange,提问作者user8845321
相关产品推荐
相关产品推荐

