Created
April 18, 2019 13:52
-
-
Save rajesh-vi/ef2df2d40197bc675bedf4d4728c5ca0 to your computer and use it in GitHub Desktop.
oauth2-bearer-jwt-handler lambda function
This file contains 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
require('dotenv').config(); | |
const JwtTokenHandler = require('oauth2-bearer-jwt-handler').JwtTokenHandler; | |
const AuthPolicy = require('./auth-policy'); | |
const fs = require('fs'); | |
const jwtTokenHandler = new JwtTokenHandler({ | |
issuer: process.env.ISSUER, | |
audience: process.env.AUDIENCE, | |
jwks: fs.readFileSync('keys.json', 'utf8') | |
}); | |
exports.handler = function(event, context) { | |
// console.log('keys.json : ', fs.readFileSync('keys.json', 'utf8') ); | |
// console.log('event :', event); | |
jwtTokenHandler.verifyRequest( | |
{ | |
headers: { authorization: event.authorizationToken } | |
}, | |
function(err, claims) { | |
if (err) { | |
console.log('Failed to validate bearer token', err); | |
return context.fail('Unauthorized'); | |
} | |
console.log('request principal: ' + claims); | |
var apiOptions = {}; | |
const arnParts = event.methodArn.split(':'); | |
const apiGatewayArnPart = arnParts[5].split('/'); | |
const awsAccountId = arnParts[4]; | |
apiOptions.region = arnParts[3]; | |
apiOptions.restApiId = apiGatewayArnPart[0]; | |
apiOptions.stage = apiGatewayArnPart[1]; | |
const method = apiGatewayArnPart[2]; | |
const resource = '/'; // root resource | |
if (apiGatewayArnPart[3]) { | |
resource += apiGatewayArnPart[3]; | |
} | |
const policy = new AuthPolicy(claims.sub, awsAccountId, apiOptions); | |
if (claims.hasScopes('http://myapp.com/scp/silver')) { | |
policy.allowMethod(AuthPolicy.HttpVerb.GET, "/planets"); | |
} | |
if (claims.hasScopes('http://myapp.com/scp/gold')) { | |
policy.allowMethod(AuthPolicy.HttpVerb.GET, "/moons"); | |
} | |
policy.allowMethod(AuthPolicy.HttpVerb.HEAD, "*"); | |
policy.allowMethod(AuthPolicy.HttpVerb.OPTIONS, "*"); | |
return context.succeed(policy.build()); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment