[英]AWS CDK - Cognito UserPool authorizer on API Gateway not working
[英]Custom Authorizer AWS CDK
我正在尝试使用 CDK 将自定义授权方附加到 API。
我正在使用 Cognito 进行用户管理。
我想通过自定义授权方实现的是,
我找不到任何关于如何将自定义授权器附加到 API 的示例或文档。我如何附加自定义授权器,或者如果它在 CDK 中不受支持,是否有解决方法来满足要求?
以下内容可能会帮助您获得想要实现的目标。 目前addMethod
上的authorizer
者尚未实现,因此您需要覆盖。
const api = new RestApi(this, 'RestAPI', {
restApiName: 'Rest-Name',
description: 'API for journey services.',
});
const putIntegration = new LambdaIntegration(handler);
const auth = new CfnAuthorizer(this, 'CustomAuthorizer', {
name: 'custom-authorizer',
type: AuthorizationType.CUSTOM,
...
});
const post = api.root.addMethod('PUT', putIntegration, { authorizationType: AuthorizationType.CUSTOM });
const postMethod = post.node.defaultChild as CfnMethod;
postMethod.addOverride('Properties.AuthorizerId', { Ref: auth.logicalId });
这附加了创建的authorizer
你必须:
最后,请求在 Header 中添加令牌。 API 网关将使用 Cognito 对其进行验证。 如果此通过,您的 lambda 将被触发,如果您可以找到声明event.requestContext.authorizer.claims 。 有一些方法可以做到这一点,请点击此链接
要补充上一个答案,截至 2021 年,您可以使用[CognitoUserPoolsAuthorizer][1]
代替,以便您可以使用以下内容:
您应该配置 Cognito 授权方并附加到您创建的 API。
创建授权人
创建 API 网关,将认知授权器附加到 api
创建资源和方法
指定集成代理和授权人
const cognitoAuthorizer = new api.CognitoUserPoolsAuthorizer(this, 'cognitoApiAuthorizer', { cognitoUserPools: [ cognito.UserPool.fromUserPoolId( this, "existing-userpool", this.props.userPoolId, ), ], }); const apiGateway = new api.RestApi(this, 'rest-api', { restApiName: 'assets-api', defaultMethodOptions: { authorizationType: api.AuthorizationType.COGNITO, authorizer: cognitoAuthorizer, } }); const putIntegration = new LambdaIntegration(handler); const resourceA = apiGateway.root.addResource('resourceA'); resourceA.addMethod('PUT', putIntegration, { authorizer: { authorizationType: api.AuthorizationType.COGNITO, authorizerId: cognitoAuthorizer.authorizerId, } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.