forked from auth0/node-jsonwebtoken
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (48 loc) · 1.57 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
62
63
64
65
66
var jws = require('jws');
module.exports.decode = function (jwt) {
return jws.decode(jwt).payload;
};
module.exports.sign = function(payload, secretOrPrivateKey, options) {
options = options || {};
var header = {typ: 'JWT', alg: options.algorithm || 'HS256'};
payload.iat = Date.now();
if (options.expiresInMinutes) {
var ms = options.expiresInMinutes * 60 * 1000;
payload.exp = payload.iat + ms;
}
if (options.audience)
payload.aud = options.audience;
if (options.issuer)
payload.iss = options.issuer;
if (options.subject)
payload.sub = options.subject;
var signed = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey});
return signed;
};
module.exports.verify = function(jwtString, secretOrPublicKey, options, callback) {
if ((typeof options === 'function') && !callback) callback = options;
if (!options) options = {};
var valid;
try {
valid = jws.verify(jwtString, secretOrPublicKey);
}
catch (e) {
return callback(e);
}
if (!valid)
return callback(new Error('invalid signature'));
var payload = this.decode(jwtString);
if (payload.exp) {
if (Date.now() >= payload.exp)
return callback(new Error('jwt expired'));
}
if (payload.aud && options.audience) {
if (payload.aud !== options.audience)
return callback(new Error('jwt audience invalid. expected: ' + payload.aud));
}
if (payload.iss && options.issuer) {
if (payload.iss !== options.issuer)
return callback(new Error('jwt issuer invalid. expected: ' + payload.iss));
}
callback(null, payload);
};