As mentioned in this article, there are two types of Lambda Authorizers but long story short, we will take advantage of the more complete one, called Lambda Request Authorizer, which provides all the request information needed for very customized validations.
Let’s get into some code.
To have a custom JWT token to validate, we need to implement a token generator, an authentication endpoint.
For the sake of simplicity, the lambda function parses the body and generates a JWT with the username and expiration for 1 hour.
after calling the /login endpoint, we get a token
The authorizer itself is a very simple lambda that returns a specific AWS policy-like JSON which will either ALLOW or DENY the call to the lambda behind.
The lambda authorizer will access the request headers, try to find the token property, and verify it against the secret.
If an application needs to extract data from the token, we can even let the authorizer do it and pass it along in the Context
The secure function used as an example isn’t the most useful of the functions as we mainly focused on how to configure our template to be secure by default.
By creating the API resource, we can specify a default authorizer that will get called for any endpoint.
The following template enforces the authorizer for any endpoint in this API and therefore any request made to any specific endpoint shall execute two lambdas (sounds pricy!) unless we specify the ReauthorizeEvery property:
The ReauthorizeEvery property allows for caching lambda authorizer responses for the same Identity, which in this case is the token headers property.
As you might have noticed, all of these resources are being provisioned from the same template but that’s not really how functionalities should be organized within the companies repositories…
In large companies, with distributed teams, it is more likely that the functionalities are written within certain repositories while the authorizers and login APIs in another.
The catch is how the API authorizer utilizes the FunctionArn attribute to configure its authorizers.
It is possible to achieve the decoupling by utilizing a service such as Parameter Store or Secrets Manager to store the Authorizers ARNs and inject the ARNs into the SAM Template using the parameter-overrides option.
Thank you for getting this far, that’s it for today.
Please leave your feedback or any suggestion and keep being awesome!
Also, check out the whole project on my Github repo.