forked from auth0-samples/jwt-rsa-aws-custom-authorizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
85 lines (68 loc) · 2.33 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
require('dotenv').config({ silent: true });
var jwksClient = require('jwks-rsa');
var jwt = require('jsonwebtoken');
var getPolicyDocument = function (effect, resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17'; // default version
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke'; // default action
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
return policyDocument;
}
// extract and return the Bearer Token from the Lambda event parameters
var getToken = function (params) {
var token;
if (!params.type || params.type !== 'TOKEN') {
throw new Error("Expected 'event.type' parameter to have value TOKEN");
}
var tokenString = params.authorizationToken;
if (!tokenString) {
throw new Error("Expected 'event.authorizationToken' parameter to be set");
}
var match = tokenString.match(/^Bearer (.*)$/);
if (!match || match.length < 2) {
throw new Error("Invalid Authorization token - '" + tokenString + "' does not match 'Bearer .*'");
}
return match[1];
}
module.exports.authenticate = function (params, cb) {
console.log(params);
var token = getToken(params);
var client = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 10, // Default value
jwksUri: process.env.JWKS_URI
});
var decoded = jwt.decode(token, { complete: true });
var kid = decoded.header.kid;
client.getSigningKey(kid, function (err, key) {
if(err)
{
cb(err);
}
else
{
var signingKey = key.publicKey || key.rsaPublicKey;
jwt.verify(token, signingKey, { audience: process.env.AUDIENCE, issuer: process.env.TOKEN_ISSUER },
function (err, decoded) {
if (err) {
cb(err);
}
else {
cb(null, {
principalId: decoded.sub,
policyDocument: getPolicyDocument('Allow', params.methodArn),
context: {
scope: decoded.scope
}
});
}
});
}
});
}