Last active
June 21, 2023 15:06
-
-
Save mikaelvesavuori/cc5ba274554dfc774ef1f327182c854b to your computer and use it in GitHub Desktop.
Example of an AWS Lambda authorizer function that runs authentication and authorization on a request. Some parts are made up or missing here. Adapted and simplified from production code, using Auth0 and GitHub as the identity provider.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jwt from 'jsonwebtoken'; | |
import jwksClient from 'jwks-rsa'; | |
import { MikroLog } from 'mikrolog'; | |
const logger = MikroLog.start(); | |
const keyClient: any = (jwksUri: string) => | |
jwksClient({ | |
cache: true, | |
cacheMaxAge: 86400000, | |
rateLimit: true, | |
jwksRequestsPerMinute: 10, | |
jwksUri | |
}); | |
const verificationOptions: any = (audience: string, issuer: string) => { | |
return { | |
algorithms: 'RS256', | |
audience, | |
issuer | |
}; | |
}; | |
/** | |
* @description Authenticate user by validating and verifying their JWT token. | |
*/ | |
export async function authenticate(token: string): Promise<Record<string, any>> { | |
const JWKS_URI = process.env.JWKS_URI || ''; | |
const AUDIENCE = process.env.AUDIENCE || ''; | |
const ISSUER = process.env.ISSUER || ''; | |
if (!JWKS_URI || !AUDIENCE || !ISSUER) throw new Error('MissingAuthorizerEnvVarsError'); | |
const decodedToken: any = jwt.decode(token, { complete: true }); | |
const kid = decodedToken.header.kid; | |
const result: boolean = await new Promise((resolve, reject) => { | |
keyClient(JWKS_URI).getSigningKey(kid, (err: any, key: any) => { | |
if (err) logger.log(err); | |
const signingKey = key.publicKey || key.rsaPublicKey; | |
try { | |
jwt.verify(token, signingKey, verificationOptions(AUDIENCE, ISSUER), (error) => { | |
if (error) resolve(false); | |
else resolve(true); | |
}); | |
} catch (error: any) { | |
logger.error(error); | |
reject(error); | |
} | |
}); | |
}); | |
return { | |
isValid: result, | |
nickname: decodedToken.payload.nickname, | |
sub: decodedToken.payload.sub | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment