5

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?

Lasitha Yapa
  • 4,309
  • 8
  • 38
  • 57

2 Answers2

3

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

amwill04
  • 1,330
  • 1
  • 11
  • 18
  • 2
    Hey, there is an `authorizer` option on `addMethod` now: api.root.addMethod('PUT', putIntegration, { authorizationType: AuthorizationType.CUSTOM, authorizer: { authorizerId: authorizer.ref } } – vladvel Oct 07 '19 at 14:38
-3

To add on to the previous answer, as of 2021 there's [CognitoUserPoolsAuthorizer][1] that you can use instead so you can use the following:

You should configure Cognito authorizer and attach to the API you created.

  1. create authorizer

  2. create API gateway, attach the cognito authorizer to the api

  3. create resource and method

  4. specify the integration proxy and authorizer

     const cognitoAuthorizer = new api.CognitoUserPoolsAuthorizer(this, 'cognitoApiAuthorizer', {
       cognitoUserPools: [
         cognito.UserPool.fromUserPoolId(
           this,
           "existing-userpool",
           this.props.userPoolId,
         ),
       ],
     });
    
     const apiGateway = new api.RestApi(this, 'rest-api', {
       restApiName: 'assets-api',
       defaultMethodOptions: {
         authorizationType: api.AuthorizationType.COGNITO,
         authorizer: cognitoAuthorizer,
       }
     });
     const putIntegration = new LambdaIntegration(handler);
     const resourceA = apiGateway.root.addResource('resourceA');
     resourceA.addMethod('PUT', putIntegration, {
       authorizer: {
         authorizationType: api.AuthorizationType.COGNITO,
         authorizerId: cognitoAuthorizer.authorizerId,
       }
     });
    
unacorn
  • 827
  • 10
  • 27