繁体   English   中英

自定义授权方 AWS CDK

[英]Custom Authorizer AWS CDK

我正在尝试使用 CDK 将自定义授权方附加到 API。

我正在使用 Cognito 进行用户管理。

我想通过自定义授权方实现的是,

  • 检查用户是否有权限使用API
  • 识别用户的email(userId),附加到请求体中
  • 使用 email 里面的 API lambda

我找不到任何关于如何将自定义授权器附加到 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

你必须:

  • 创建 api 网关
  • 在 api 网关中将 Cognito 设置为授权方
  • 在您的方法中设置授权
  • 将您与 lambda 的集成设置为“使用 Lambda 代理集成”。 默认情况下,LambdaIntegration 属性的值为 true,所以不用担心

最后,请求在 Header 中添加令牌。 API 网关将使用 Cognito 对其进行验证。 如果此通过,您的 lambda 将被触发,如果您可以找到声明event.requestContext.authorizer.claims 有一些方法可以做到这一点,请点击此链接

要补充上一个答案,截至 2021 年,您可以使用[CognitoUserPoolsAuthorizer][1]代替,以便您可以使用以下内容:

您应该配置 Cognito 授权方并附加到您创建的 API。

  1. 创建授权人

  2. 创建 API 网关,将认知授权器附加到 api

  3. 创建资源和方法

  4. 指定集成代理和授权人

     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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM