Creating Lambda authorizer for HTTP API?

Is there a way to attach a custom lambda authorizer to HTTP API?

You can setup it through the AWS console UI, or you can create your own authorizer function. Like:

serverless.yml

functions:
   hello:
     handler: handler.hello
     events:
     - http:
        path: hello
        method: get
        cors: true
        authorizer:
          type: TOKEN
          name: authorizerFun
          identitySource: method.request.header.Authorization
          resultTtlInSeconds: 0

authorizerFun:
  handler: authorizer.authorizerFun

authorizer.authorizerFun

const generatePolicy = (user, effect, resource) => {
   const authResponse = {
   principalId: user.id || 'anonymous'
 };

 if (effect && resource) {
   const policyDocument = {
     Version: '2012-10-17',
     Statement: [
       {
         Action: 'execute-api:Invoke',
         Effect: effect,
         Resource: resource
       }
     ]
   };

   authResponse.policyDocument = policyDocument;
 }

authResponse.context = {
  role: user.role
};
return authResponse; };

export const authorizerFun = (event, context) => {
 const authorizationToken = event.authorizationToken;

 console.log(authorizationToken);

 switch (authorizationToken) {
   case 'manager':
     context.succeed(generatePolicy({ id: 1, role: 'MANAGER' }, 'Allow', '*'));
     break;
   case 'tenant':
     context.succeed(generatePolicy({ id: 2, role: 'TENANT' }, 'Allow', '*'));
     break;
   default:
     context.fail('error');
 }
};

Thanx @sgyyz for the reply :slightly_smiling_face:
The above is an implementation of how to attach a lambda authorizer for REST API but I haven’t found a way to attach a lambda authorizer for HTTP API through serverless.yml even though HTTP APIs support lambda authorizers.

2 Likes