Skip to content

Instantly share code, notes, and snippets.

@joawan
Created April 15, 2020 19:54
Show Gist options
  • Save joawan/d92b76a6a3b98b73d39ea8b21a217129 to your computer and use it in GitHub Desktop.
Save joawan/d92b76a6a3b98b73d39ea8b21a217129 to your computer and use it in GitHub Desktop.
Token introspection as Lambda Authorizer
const tokenIntrospection = require('token-introspection');
const introspect = tokenIntrospection({
jwks_uri: process.env.JWKS_URI,
jwks_cache_time: 60 * 60,
});
const hasScope = (token, scope) => token.scope && token.scope.split(' ').includes(scope);
const generatePolicy = (principalId, effect, resource, context = {}) => ({
principalId,
context,
policyDocument: {
Version: '2012-10-17',
Statement: [{
Effect: effect,
Action: 'execute-api:Invoke',
Resource: resource,
}],
},
});
exports.handler = async (event) => {
let token;
try {
[, token] = event.authorizationToken.match(/^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/);
} catch (e) {
throw new Error('Unauthorized');
}
try {
const data = await introspect(token);
const effect = hasScope(data, process.env.SCOPE) ? 'Allow' : 'Deny';
return generatePolicy(data.sub || data.client_id, effect, event.methodArn, data);
} catch (e) {
throw new Error('Unauthorized');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment