Get started with Lambda Authorizers
Tags: beginners, aws, security, lambdafunction
Published: 2022-03-16 05:36:24


## Overview
  In this blog post, we will be learning about **Lambda Authorizers** and how they can help you in your authorization journey. We will also see how you can create a lambda authorizer and attach it to your API.

## What's Lambda Authorizer anyway!
  In simple words, they act as bouncers for the API Gateway. When a user calls an API method, it gets passed to the Lambda Authorizer via API gateway to check the caller’s identity.
  > Under the hood, Lambda Authorizer is a plain old Lambda function.

## Do **I HAVE TO** learn about them?
Lambda Authorizers (also called Custom Authorizers) are a great way to centralize your auth logic so that you don’t have to go around importing your auth library in every module.
Let’s say you want to change your auth logic, you can just redeploy your custom authorizer and you’re done.  

Another aspect is caching. If your auth logic makes a remote call, imagine the added latency with every request that comes in! By using the Lambda Authorizer, you can cache the remote call for up to an hour and save up on cost as well as time! 
So, are you interested? Let’s go into more detail.

## How Does it work?
![API Gateway Lambda authorization workflow](https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/blog-Picture1.png)
1.  The Client calls the API bearing a token which ends up at the API Gateway.
2.  API Gateway checks whether a Lambda authorizer is configured for the method. If yes, then the Lambda Function (which acts as Lambda Authorizer) is called.
3.  The Lambda function authenticates the caller using the logic that is provided.
4.  If the call succeeds, the Lambda function grants access by returning an output object containing at least an IAM policy and a principal identifier.
5.  API Gateway evaluates the policy and returns suitable HTTP code. In case of enabled caching, the cached policy is returned so that the Lambda authorizer function will not be invoked again.

## Let’s put this to test
We are going to create a token based authorizer.

###  Step 1:
Go to aws `console > Lambda > Functions > Create function` and set it up as shown in the image.  

<img src="https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/create-function.png" alt="lambda function creation form" style="height: 400px;"/><br/>  

### Step 2:
Click on create function and put this code in the editor.

```
exports.handler =  function(event, context, callback) {
    var token = event.authorizationToken;
    switch (token) {
        case 'allow':
            callback(null, generatePolicy('user', 'Allow', event.methodArn));
            break;
        case 'deny':
            callback(null, generatePolicy('user', 'Deny', event.methodArn));
            break;
    }
};

var generatePolicy = function(principalId, effect, resource) {
    var authResponse = {};
    
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17'; 
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke'; 
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    
    authResponse.context = {
        "stringKey": "stringval",
        "numberKey": 123,
        "booleanKey": true
    };
    return authResponse;
}
```
###  Step 3:
Test it and Choose Deploy.

### Step 4:
Now we have a lambda Function to use it as an Authorizer is ready. Let’s head to the API Gateway and attach it to the actual API.

Go to the API Gateway Console and choose your API from the API list.
Select the Authorizer like so and click on Create new Authorizer.  

![create a new authorizer button](https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/create-authorizer.png)<br/>
 

### Step 5:
You will see a dialog like below. Put the required details just like the picture and click on create.  

![create authorizer form](https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/auth-form.png)<br/>

### Step 6:
Now click on test to see if it is working as we expect it to work.  

![test authorizer screen](https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/test-authorizer.png)<br/>

If the token value is “allow”, 200 OK and an IAM policy like this should be returned.
```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Allow",
      "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/"
    }
  ]
}
```

If the token value is “deny”, 403 Forbidden and an IAM policy like this should be returned.
```
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Deny",
      "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/"
    }
  ]
}
```

### Step 7:
Once you have tested your authorizer, Let’s attach it to your API endpoints. 
Go to your API in the API gateway console and click on resources on the sidebar. Select the method  and click on Method Request.  

![method request page](https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/method-requtest.jpg)<br/>

###  Step 8:
Now you want to select the Authorization option and select the one we created.  

![authorization dropdown](https://cdn.svc.oneadvanced.com/engineering-blogs/lambda-api-authorizers/method-execution.png)<br/>

Once you do that, click on the check mark and we are done! Deploy the API and we can test it using Postman!
Now You have your own Lambda Authorizer sitting on top of your API logic, making your APIs safer than ever!!

## Lambda Authorizers are great, but let me warn you
Since we live in the real world where nothing is perfect, the same scenario applies here. We all are aware of the cold start issue of Lambda Functions, since Lambda Authorizer is also a lambda function under the hood, we might face some latency issues.
Another problem is the flexibility of it. Since the authorizer expects users to pass authorization information, imagine an endpoint where anyone can get public information about a resource and the owner of the resource gets special treatment and is returned some private data along with it.

## What next?
Good job! You have just deployed a Serverless Authorizer which can be easily modified throughout all of your your APIs. Not a small pursuit at all. Next you can read more about OAuth and JWT from our blogs and implement that logic in your custom authorizer. Feel free to follow and leave a comment on what you wanna read next.