forked from auth0-samples/jwt-rsa-aws-custom-authorizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
70 lines (59 loc) · 2.08 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
require('dotenv').config({ silent: true });
const jwksClient = require('jwks-rsa');
const jwt = require('jsonwebtoken');
const util = require('util');
const getPolicyDocument = (effect, resource) => {
const policyDocument = {
Version: '2012-10-17', // default version
Statement: [{
Action: 'execute-api:Invoke', // default action
Effect: effect,
Resource: resource,
}]
};
return policyDocument;
}
// extract and return the Bearer Token from the Lambda event parameters
const getToken = (params) => {
if (!params.type || params.type !== 'TOKEN') {
throw new Error('Expected "event.type" parameter to have value "TOKEN"');
}
const tokenString = params.authorizationToken;
if (!tokenString) {
throw new Error('Expected "event.authorizationToken" parameter to be set');
}
const match = tokenString.match(/^Bearer (.*)$/);
if (!match || match.length < 2) {
throw new Error(`Invalid Authorization token - ${tokenString} does not match "Bearer .*"`);
}
return match[1];
}
const jwtOptions = {
audience: process.env.AUDIENCE,
issuer: process.env.TOKEN_ISSUER
};
module.exports.authenticate = (params) => {
console.log(params);
const token = getToken(params);
const decoded = jwt.decode(token, { complete: true });
if (!decoded || !decoded.header || !decoded.header.kid) {
throw new Error('invalid token');
}
const client = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 10, // Default value
jwksUri: process.env.JWKS_URI
});
const getSigningKey = util.promisify(client.getSigningKey);
return getSigningKey(decoded.header.kid)
.then((key) => {
const signingKey = key.publicKey || key.rsaPublicKey;
return jwt.verify(token, signingKey, jwtOptions);
})
.then((decoded)=> ({
principalId: decoded.sub,
policyDocument: getPolicyDocument('Allow', params.methodArn),
context: { scope: decoded.scope }
}));
}