AWS CDK 用户池授权方

AWS CDK user pool authorizer

我正在尝试使用 AWS-CDK 创建一个 API 网关,并使用 Cognito 用户池授权方保护 REST 端点。

我找不到任何例子说明如何做到这一点。我认为它应该看起来像这样,但也许我需要的方法不存在?

const cdk       = require('@aws-cdk/cdk');
const lambda    = require('@aws-cdk/aws-lambda');
const apigw     = require('@aws-cdk/aws-apigateway');

const path  = require('path');

// 
// Define the stack:
class MyStack extends cdk.Stack {
    constructor (parent, id, props) {
        super(parent, id, props);    

        var tmethodHandler = new lambda.Function(this, 'test-lambda', {
            runtime: lambda.Runtime.NodeJS810,
            handler: 'index.handler',
            code: lambda.Code.directory( path.join( __dirname, 'lambda')),
        });

        var api         = new apigw.RestApi(this, 'test-api');

        const tmethod   = api.root.addResource('testmethod');

        const tmethodIntegration    = new apigw.LambdaIntegration(tmethodHandler);

        tmethod.addMethod('GET', getSessionIntegration, {
            authorizationType: apigw.AuthorizationType.Cognito,
            authorizerId : 'crap!!!?'
        });

    }
}

class MyApp extends cdk.App {
    constructor (argv) {
        super(argv);

        new MyStack(this, 'test-apigw');
    }
}

console.log(new MyApp(process.argv).run());

我想出了一个看起来像机制的东西...我能够让它像这样工作:

var auth = new apigw.cloudformation.AuthorizerResource(this, 'myAuthorizer', {
    restApiId: api.restApiId,
    authorizerName: 'mypoolauth',
    authorizerResultTtlInSeconds: 300,
    identitySource: 'method.request.header.Authorization',
    providerArns: [ 'arn:aws:cognito-idp:us-west-2:redacted:userpool/redacted' ],
    type: "COGNITO_USER_POOLS"
});

tmethod.addMethod('GET', getSessionIntegration, {
    authorizationType: apigw.AuthorizationType.Cognito,
    authorizerId : auth.authorizerId
});

现在了解如何在 API 网关上启用 CORS headers...

确实如此。没有通过复制和粘贴来执行此操作的示例;)。这是我创建 AWS Cognito 用户池并使用基于 Java 版本 0.24.1.

的 AWS CDK 网关和 lambda 函数连接用户 pol 授权方的示例

此示例只是为名为 "Foo" 的函数提供受保护 API 的示例。

  • Cognito 用户池
  • API 网关
  • 拉姆达
  • DynamoDB

    // -----------------------------------------------------------------------
    // Cognito User Pool
    // -----------------------------------------------------------------------
    CfnUserPool userPool = new CfnUserPool(this, "cognito",
        CfnUserPoolProps.builder()
            .withAdminCreateUserConfig(
                AdminCreateUserConfigProperty.builder()
                    .withAllowAdminCreateUserOnly(false)
                    .build())
            .withPolicies(
                PoliciesProperty.builder()
                    .withPasswordPolicy(
                        PasswordPolicyProperty.builder()
                            .withMinimumLength(6)
                            .withRequireLowercase(false)
                            .withRequireNumbers(false)
                            .withRequireSymbols(false)
                            .withRequireUppercase(false)
                            .build()
                    )
                    .build()
            )
            .withAutoVerifiedAttributes(Arrays.asList("email"))
            .withSchema(Arrays.asList(
                CfnUserPool.SchemaAttributeProperty.builder()
                    .withAttributeDataType("String")
                    .withName("email")
                    .withRequired(true)
                    .build()))
            .build());
    
    // -----------------------------------------------------------------------
    // Cognito User Pool Client
    // -----------------------------------------------------------------------
    new CfnUserPoolClient(this, "cognitoClient",
        CfnUserPoolClientProps.builder()
            .withClientName("UserPool")
            .withExplicitAuthFlows(Arrays.asList("ADMIN_NO_SRP_AUTH"))
            .withRefreshTokenValidity(90)
            .withUserPoolId(userPool.getRef())
            .build());
    
    // -----------------------------------------------------------------------
    // Lambda function
    // -----------------------------------------------------------------------
    Function function = new Function(this, "function.foo",
        FunctionProps.builder()
            // lamda code located in /functions/foo
            .withCode(Code.asset("functions/foo"))
            .withHandler("index.handler")
            .withRuntime(Runtime.NODE_J_S810)
            .build());
    
    // -----------------------------------------------------------------------
    // DynamoDB Table
    // -----------------------------------------------------------------------
    Table table = new Table(this, "dynamodb.foo", TableProps.builder()
        .withTableName("foo")
        .withPartitionKey(Attribute.builder()
            .withName("id")
            .withType(AttributeType.String)
            .build())
        .build());
    
    // GRANTS function -> table
    table.grantReadWriteData(function.getRole());
    
    // -----------------------------------------------------------------------
    // API Gateway
    // -----------------------------------------------------------------------
    
    // API Gateway REST API with lambda integration
    LambdaIntegration lambdaIntegration = new LambdaIntegration(function);
    RestApi restApi = new RestApi(this, "foo");
    
    // Authorizer configured with cognito user pool
    CfnAuthorizer authorizer = new CfnAuthorizer(this, "authorizer",
        CfnAuthorizerProps.builder()
            .withName("cognitoAuthorizer")
            .withRestApiId(restApi.getRestApiId())
            .withIdentitySource("method.request.header.Authorization")
            .withProviderArns(Arrays.asList(userPool.getUserPoolArn()))
            .withType("COGNITO_USER_POOLS")
            .build());
    
    // Bind authorizer to API ressource
    restApi.getRoot().addMethod("ANY", lambdaIntegration, MethodOptions
        .builder()
          .withAuthorizationType(AuthorizationType.Cognito)
          .withAuthorizerId(authorizer.getAuthorizerId())
        .build());
    

之前的答案不再有效,因为 authorizerId 属性 已替换为 authorizer,目前尚未完全实现。

相反,它可以通过使用底层 CfnResource 对象来完成,as described in the official guide

这里有 Python 代码作为例子:

from aws_cdk import cdk
from aws_cdk import aws_apigateway


class Stk(cdk.Stack):
    def __init__(self, app, id):
        super().__init__(app, id)

        api_gw = aws_apigateway.RestApi(self, 'MyApp')
        post_method = api_gw.root.add_method(http_method='POST')

        # Create authorizer using low level CfnResource
        api_gw_authorizer = aws_apigateway.CfnAuthorizer(
            scope=self,
            id='my_authorizer',
            rest_api_id=api_gw.rest_api_id,
            name='MyAuth',
            type='COGNITO_USER_POOLS',
            identity_source='method.request.header.name.Authorization',
            provider_arns=[
                'arn:aws:cognito-idp:eu-west-1:123456789012:userpool/'
                'eu-west-1_MyCognito'])

        # Get underlying post_method Resource object. Returns CfnMethod
        post_method_resource = post_method.node.find_child('Resource')
        # Add properties to low level resource
        post_method_resource.add_property_override('AuthorizationType',
                                                   'COGNITO_USER_POOLS')
        # AuthorizedId uses Ref, simulate with a dictionaty
        post_method_resource.add_property_override(
                'AuthorizerId',
                {"Ref": api_gw_authorizer.logical_id})


app = cdk.App()
stk = Stk(app, "myStack")

app.synth()

这是我在 TypeScript 中的解决方案(基于 bgdnlp 的响应)

import { App, Stack, Aws } from '@aws-cdk/core';
import { Code, Function, Runtime } from '@aws-cdk/aws-lambda';
import { LambdaIntegration, RestApi, CfnAuthorizer, CfnMethod } from '@aws-cdk/aws-apigateway';

const app = new App();
const stack = new Stack(app, `mystack`);
const api = new RestApi(stack, `myapi`);

const region = Aws.REGION;
const account = Aws.ACCOUNT_ID;
const cognitoArn = `arn:aws:cognito-idp:${region}:${account}:userpool/${USER_POOL_ID}`;

const authorizer = new CfnAuthorizer(stack, 'Authorizer', {
  name: `myauthorizer`,
  restApiId: api.restApiId,
  type: 'COGNITO_USER_POOLS',
  identitySource: 'method.request.header.Authorization',
  providerArns: [cognitoArn],
});

const lambda = new Function(stack, 'mylambda', {
  runtime: Runtime.NODEJS_10_X,
  code: Code.asset('dist'),
  handler: `index.handler`,
});

const integration = new LambdaIntegration(lambda);

const res = api.root.addResource('hello');

const method = res.addMethod('GET', integration);

const child = method.node.findChild('Resource') as CfnMethod;

child.addPropertyOverride('AuthorizationType', 'COGNITO_USER_POOLS');

child.addPropertyOverride('AuthorizerId', { Ref: authorizer.logicalId });

September 2019 开始,@bgdnip 的回答并未准确翻译为 typescript。我得到它与以下工作:

const api = new RestApi(this, 'RestAPI', {
    restApiName: 'Rest-Name',
    description: 'API for journey services.',
});

const putIntegration = new LambdaIntegration(handler);

const auth = new CfnAuthorizer(this, 'APIGatewayAuthorizer', {
    name: 'customer-authorizer',
    identitySource: 'method.request.header.Authorization',
    providerArns: [providerArn.valueAsString],
    restApiId: api.restApiId,
    type: AuthorizationType.COGNITO,
});

const post = api.root.addMethod('PUT', putIntegration, { authorizationType: AuthorizationType.COGNITO });
const postMethod = post.node.defaultChild as CfnMethod;
postMethod.addOverride('Properties.AuthorizerId', { Ref: auth.logicalId });

这是来自https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html#cfn_layer_resource_props

十月更新

以上内容已经过时且不必要,可以通过以下 aws-cdk 1.12.0

来实现
const api = new RestApi(this, 'RestAPI', {
    restApiName: 'Rest-Name',
    description: 'API for journey services.',
});

const putIntegration = new LambdaIntegration(handler);

const auth = new CfnAuthorizer(this, 'APIGatewayAuthorizer', {
    name: 'customer-authorizer',
    identitySource: 'method.request.header.Authorization',
    providerArns: [providerArn.valueAsString],
    restApiId: api.restApiId,
    type: AuthorizationType.COGNITO,
});

const post = api.root.addMethod('PUT', putIntegration, {
    authorizationType: AuthorizationType.COGNITO,
    authorizer: { authorizerId: auth.ref }
});

对于使用 Java 版本的 CDK 的怪人(比如我),您可以在 Cfn 结构上使用 setter:

final UserPool userPool = ...
final RestApi restApi = ...
final LambdaIntegration integration = ...
final Method method = restApi.getRoot().addMethod("GET", integration);

final CfnAuthorizer cognitoAuthorizer = new CfnAuthorizer(this, "CfnCognitoAuthorizer",
        CfnAuthorizerProps.builder()
                .name("CognitoAuthorizer")
                .restApiId(restApi.getRestApiId())
                .type("COGNITO_USER_POOLS")
                .providerArns(Arrays.asList(userPool.getUserPoolArn()))
                .identitySource("method.request.header.Authorization")
                .build());

final CfnMethod cfnMethod = (CfnMethod) method.getNode().getDefaultChild();
cfnMethod.setAuthorizationType("COGNITO_USER_POOLS");
cfnMethod.setAuthorizerId(cognitoAuthorizer.getRef());

你必须:

  • 创建 api 网关
  • 在 api 网关中将 Cognito 设置为授权方
  • 在你的方法中设置权限
  • 将您与 lambda 的集成设置为 'Use Lambda Proxy integration'。 LambdaIntegration 属性默认为真,所以不用担心

最后,在Header 中添加token 的请求。 API 网关将使用 Cognito 对其进行验证。如果这个通过,你的 lambda 将被触发,如果你可以找到声明 event.requestContext.authorizer.claims.


const lambda = require("@aws-cdk/aws-lambda");
const apiGateway = require('@aws-cdk/aws-apigateway'); 

 const api = new apiGateway.RestApi(
      this,
      '<id-ApiGateway>',
      {
        restApiName: '<ApiGateway-name>',
      },
    );

    const auth = new apiGateway.CfnAuthorizer(this, '<id>', {
      name: "<authorizer-name>",
      type: apiGateway.AuthorizationType.COGNITO,
      authorizerResultTtlInSeconds: 300,
      identitySource: "method.request.header.Authorization",
      restApiId: api.restApiId,
      providerArns: ['<userPool.userPoolArn>'],
    });

    const myLambda= new lambda.Function(this, "<id>", {
      functionName: '<lambda-name>',
      runtime: lambda.Runtime.NODEJS_10_X,
      handler: "<your-handler>",
      code: lambda.Code.fromAsset("<path>"), // TODO: modify the way to get the path
    });

      const lambdaIntegration = new apiGateway.LambdaIntegration(myLambda);

      const resource = api.root.resourceForPath('<your-api-path>');
      // When the API will be deployed, the URL will look like this
      // https://xxxxxx.execute-api.us-east-2.amazonaws.com/dev/<your-api-path>

      const authorizationOptions = {
        apiKeyRequired: false,
        authorizer: {authorizerId: auth.ref},
        authorizationType: 'COGNITO_USER_POOLS'
      };

      resource.addMethod(
        GET, // your method
        lambdaIntegration,
        authorizationOptions
      );

从 v1.88 开始,CDK 直接支持此功能

const userPool = new cognito.UserPool(this, 'UserPool');

const auth = new apigateway.CognitoUserPoolsAuthorizer(this, 'booksAuthorizer', {
  cognitoUserPools: [userPool]
});

declare const books: apigateway.Resource;
books.addMethod('GET', new apigateway.HttpIntegration('http://amazon.com'), {
  authorizer: auth,
  authorizationType: apigateway.AuthorizationType.COGNITO,
});

AWS CDK API V1 Reference

AWS CDK API V2 Reference