-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
61 lines (54 loc) · 1.51 KB
/
index.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
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
const keyClient = jwksClient({
cache: true,
cacheMaxAge: 86400000, //value in ms
rateLimit: true,
jwksRequestsPerMinute: 10,
strictSsl: true,
jwksUri: process.env.JWKS_URI
})
const verificationOptions = {
// verify claims, e.g.
// "audience": "urn:audience"
"algorithms": "RS256"
}
const allow = {
"principalId": "user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": process.env.RESOURCE
}
]
}
}
function getSigningKey (header = decoded.header, callback) {
keyClient.getSigningKey(header.kid, function(err, key) {
const signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
})
}
function extractTokenFromHeader(e) {
if (e.authorizationToken && e.authorizationToken.split(' ')[0] === 'Bearer') {
return e.authorizationToken.split(' ')[1];
} else {
return e.authorizationToken;
}
}
function validateToken(token, callback) {
jwt.verify(token, getSigningKey, verificationOptions, function (error) {
if (error) {
callback("Unauthorized")
} else {
callback(null, allow)
}
})
}
exports.handler = (event, context, callback) => {
let token = extractTokenFromHeader(event) || '';
validateToken(token, callback);
}