20

我正在尝试使用 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());
4

8 回答 8

23

截至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 }
});
于 2019-09-30T14:42:20.383 回答
5

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

相反,它可以通过使用底层 CfnResource 对象来完成,如官方指南中所述

下面以 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()
于 2019-06-23T14:39:07.357 回答
5

这是我在 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 });
于 2019-07-14T23:53:14.963 回答
3

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

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 Gateway 上启用 CORS 标头...

于 2018-10-09T22:18:04.120 回答
3

确实。没有例子可以通过复制和粘贴来做到这一点;)。这是我使用基于 Java 版本 0.24.1 的 AWS CDK 创建 AWS cognito 用户池并将用户 pol 授权者与 API 网关和 lambda 函数连接的示例。

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

  • Cognito 用户池
  • API 网关
  • 拉姆达
  • 动态数据库

    // -----------------------------------------------------------------------
    // 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());
    
于 2019-03-04T13:11:50.323 回答
3

你必须:

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

最后,发出请求,在 Header 中添加令牌。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
      );

于 2020-05-16T21:12:25.090 回答
2

对于使用 Java 版本 CDK 的怪人(像我一样),您可以利用 Cfn 构造上的设置器:

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());
于 2020-04-02T19:18:17.207 回答
0

从 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 参考

AWS CDK API V2 参考

于 2022-01-04T19:38:09.877 回答