首页 > 解决方案 > AWS CDK 用户池授权者

问题描述

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

标签: javascriptaws-sdkamazon-cognitoaws-cdk

解决方案


截至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 }
});

推荐阅读