Simple Lambda Custom Authorizer

Using a Lambda for Authorization and Authentication on AWS API Gateway

Updated: 03 September 2023

Custom Authorizers

API Gateway allows us to handle auth by way of a lambda. AWS has two types of authorization lambdas we can use, namely:

  • SIMPLE - returns a message stating whether a user is authorized along with a context object
  • IAM - returns an IAM Policy Document stating user/resource access

We’ll be discussing at the former since it’s significantly simpler (hence the name) and is fairly poorly documented on the interwebs

Also note that I’m using SST for the definition of the Function and Api but the general concept still applies at a broader API Gateway and CDK Stack

The Authorizer Lambda

Note that the @types/aws-lambda package does not have a type def for the SIMPLE authorizer, and so I’ve provided the authorizer in JavaScript in order to keep things to the point, but in practice you should probably write more concrete types for the lambda

The expected return value for the Authorizer in SIMPLE mode looks like this:

1
interface AuthResult {
2
isAuthorized: boolean
3
context?: any
4
}

If we want to create an Authorizer Lambda that checks for a username in the Authorization header for example, we can do something Like the below:

src/lambda/auth.js

1
export const handler = async (event) => {
2
const allowedUser = process.env.ALLOWED_USER
3
4
if (!allowedUser) {
5
return {
6
isAuthorized: false,
7
}
8
}
9
10
// get the `username` from the `headers`
11
const username = event.headers.Authorization
12
13
// return unauthorized if the `username` does not match the `allowedUser`
14
if (username !== allowedUser) {
15
return {
16
isAuthorized: false,
17
}
18
}
19
20
// return authorized if the `username` matches, along with some data in the `context`. the
21
// `context` will be passed on to any lambda that's guarded by this authorizer so it's a good way
22
// to populate what we know about the user so downstream lambdas don't need to check this manually
23
return {
24
isAuthorized: true,
25
context: {
26
username,
27
},
28
}
29
}

Lastly, if you’re hooking things up manually you can find the Authorizer Settings in API Gateway for your specific API and Lambda, but if you’re using CDK/SST look to the next section for how to integrate this into your stack

The Stack

If, like me, you’re using SST for creating your API and would like to configure your Authorizer using that, you can simply add the following to your stack and attaching it to your API

1
// Authorizer Lambda Definition
2
const authHandler = new sst.Function(this, 'AuthHandler', {
3
handler: 'src/lambda/auth.handler',
4
environment: {
5
ALLOWED_USER: 'nabeel'
6
},
7
});
8
9
const authorizer = new HttpLambdaAuthorizer({
10
authorizerName: 'LambdaAuthorizer',
11
handler: authHandler,
12
responseTypes: [HttpLambdaResponseType.SIMPLE],
13
});
14
15
// Existing API Definition
16
const api = new sst.Api(this, 'Api', {
17
defaultAuthorizationType: sst.ApiAuthorizationType.CUSTOM,
18
defaultAuthorizer: authorizer,
19
defaultPayloadFormatVersion: ApiPayloadFormatVersion.V2,
20
/// rest of props

PolicyDocument Based Authorizers

In the context of Authorizers we can also have the PolicyDocument based authorizers which is the typical implementation. Without any explanation this is what one of those would look like:

This example is straight from the AWS Documentation

1
// A simple token-based authorizer example to demonstrate how to use an authorization token
2
// to allow or deny a request. In this example, the caller named 'user' is allowed to invoke
3
// a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke
4
// the request if the token value is 'deny'. If the token value is 'unauthorized' or an empty
5
// string, the authorizer function returns an HTTP 401 status code. For any other token value,
6
// the authorizer returns an HTTP 500 status code.
7
// Note that token values are case-sensitive.
8
9
exports.handler = function (event, context, callback) {
10
var token = event.authorizationToken
11
switch (token) {
12
case 'allow':
13
callback(null, generatePolicy('user', 'Allow', event.methodArn))
14
break
15
case 'deny':
16
callback(null, generatePolicy('user', 'Deny', event.methodArn))
17
break
18
case 'unauthorized':
19
callback('Unauthorized') // Return a 401 Unauthorized response
20
break
21
default:
22
callback('Error: Invalid token') // Return a 500 Invalid token response
23
}
24
}
25
26
// Help function to generate an IAM policy
27
var generatePolicy = function (principalId, effect, resource) {
28
var authResponse = {}
29
30
authResponse.principalId = principalId
31
if (effect && resource) {
32
var policyDocument = {}
33
policyDocument.Version = '2012-10-17'
34
policyDocument.Statement = []
35
var statementOne = {}
36
statementOne.Action = 'execute-api:Invoke'
37
38
statementOne.Effect = effect
39
statementOne.Resource = resource
40
policyDocument.Statement[0] = statementOne
41
authResponse.policyDocument = policyDocument
42
}
43
44
// Optional output with custom properties of the String, Number or Boolean type.
45
authResponse.context = {
46
stringKey: 'stringval',
47
numberKey: 123,
48
booleanKey: true,
49
}
50
return authResponse
51
}