'Custom Authorizer AWS CDK

I am trying to attach a custom authorizer to API using CDK.

I am using Cognito for the user management.

What I want to achieve with the custom authorizer is,

  • Check whether the user has permission to use the API
  • Identify the user's email (userId) and attach it to the request body
  • Use that email inside the API lambda

I can't find any examples or documents regarding how to attach a custom authorizer to an API. How can I attach an custom authorizer or if it's not supported in CDK is there a work around to achieve the requirements?



Solution 1:[1]

The following may help you get what you want to achieve. Currently the authorizer on the addMethod isnt implemented so you need to override.

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

This attaches the created authorizer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 amwill04