DEV Community

Konstantin
Konstantin

Posted on

Painful CDK - 1

AWS CDK is a great tool. Although it sometimes works not as expected. In this post, I'd like to share some CDK pain.

Let's take a look on the simple piece of code below. My goal is to create a new Cognito user pool authorizer and use it to protect a newly created endpoint with a lambda integration.

// create cognito authorizer:
const authorizer = new apigateway.CfnAuthorizer(this.ctx, "restApiMyResourceAuthorizer", {
      restApiId: this.restApi.restApiId,
      type: "COGNITO_USER_POOLS",
      identitySource: "method.request.header.Authorization",
      name: "restApiMyResourceAuthorizer",
      providerArns: [".."],
 });
// create a resource
const myResource: apigateway.Resource = this.restApi.root.addResource("myResource");
// add an endpoint to the Rest API resource with authorizer
myResource.addMethod(lambdaDeploymentOptions.httpMethod, new apigateway.LambdaIntegration(lambda),{
      authorizationType: apigateway.AuthorizationType.COGNITO,
      authorizer: {
        authorizerId: authorizer.node.id,
        authorizationType: apigateway.AuthorizationType.COGNITO,
      }
});
Enter fullscreen mode Exit fullscreen mode

This gives:

Invalid authorizer ID specified. Setting the authorization type to CUSTOM or COGNITO_USER_POOLS requires a valid authorizer.

There are some opened questions in the internet on this topic.
Solution I've found is a bit hacky:

const method = myResource.addMethod(lambdaDeploymentOptions.httpMethod, new apigateway.LambdaIntegration(lambda),{
    authorizationType: apigateway.AuthorizationType.COGNITO,
    authorizer: {
    authorizerId: lambdaDeploymentOptions.authorizer.node.id,
    authorizationType: apigateway.AuthorizationType.COGNITO,
  }
});

const child = method.node.findChild('Resource') as apigateway.CfnMethod;
child.addPropertyOverride('AuthorizationType', 'COGNITO_USER_POOLS');
child.addPropertyOverride('AuthorizerId', { Ref: lambdaDeploymentOptions.authorizer.logicalId });
Enter fullscreen mode Exit fullscreen mode

In case of questions: "why CfnAuthorizer, not CognitoUserPoolsAuthorizer. The reason is simple - CognitoUserPoolsAuthorizer does not allow to set Token Validation regular expression (identityValidationExpression).

P.S.
There is a general guide how to solve issues with CDK. "Escape hatches": https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html

Top comments (0)