Photo by John Cameron on Unsplash

LAMBDA AUTHORIZER ON STEROIDS

Get More Out Of Lambda Authorizer

Use Lambda context to perform more than just authorization

{
"principalId": "adrin",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow"
}
]
},
"context": {
"basic_credentials": "Basic bW9zc2FkOkVpY2htYW5u"
}
}

A Specific Scenario- Creating And Passing Basic AuthN Header To API Backend

Figure-1: The hypothetical scenario

Secret In SecretsManager

{
"key": "<super secret key used for token validation>",
"credentials": {
"username": "<basic authn user>",
"password": "<basic authn password>"
}
}

IAM Role For Lambda authorizer

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"secretsmanager:GetSecretValue",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:ap-south-1:123456789100:log-group:/aws/lambda/lambda_auth_clientid_jwt:*",
"arn:aws:secretsmanager:ap-south-1:123456789100:secret:cTrqY79Lrff1RdWtdtHM-Vd58Op"
]
},
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:ap-south-1:123456789100:*"
}
]
}

The REST API

Figure-2: Create a REST API with GET operation & HTTP integration type
Figure-3: The Method request/response & Integration request/response palette

Register Lambda As Authorizer

Figure-4: Register the lambda function as a Request Authorizer
Figure-5: Test the Lambda Authorizer
const jwt = require('jsonwebtoken');
const key = "<fetch the secret key>";
var token = jwt.sign({ user: 'adrin',
email: 'adrin.mukherjee@gmail.com'},
key, { algorithm: 'HS256', expiresIn: '1h' });console.log(token);

Configure The API

Figure-6: Attach the Lambda Authorizer to the operation/s
#set($context.requestOverride.header.Authorization =                
$context.authorizer.basic_credentials)
$input.json("$")
Figure-7: Create a new mapping template

Conclusion

Solutions architect by profession, programmer by passion and photographer by choice…