fix nbf verification. fix #152

This commit is contained in:
José F. Romaniello
2016-01-04 08:53:25 -03:00
parent f1fb176a15
commit 786d37b299
4 changed files with 50 additions and 5 deletions
+3 -4
View File
@@ -59,7 +59,7 @@ JWT.sign = function(payload, secretOrPrivateKey, options, callback) {
payload.iat = payload.iat || timestamp;
}
if (options.notBefore) {
if (typeof options.notBefore !== 'undefined') {
payload.nbf = timespan(options.notBefore);
if (typeof payload.nbf === 'undefined') {
throw new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
@@ -82,7 +82,7 @@ JWT.sign = function(payload, secretOrPrivateKey, options, callback) {
options.expiresInSeconds;
payload.exp = timestamp + expiresInSeconds;
} else if (options.expiresIn) {
} else if (typeof options.expiresIn !== 'undefined') {
payload.exp = timespan(options.expiresIn);
if (typeof payload.exp === 'undefined') {
throw new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
@@ -209,8 +209,7 @@ JWT.verify = function(jwtString, secretOrPublicKey, options, callback) {
if (typeof payload.nbf !== 'number') {
return done(new JsonWebTokenError('invalid nbf value'));
}
if (payload.nbf >= Math.floor(Date.now() / 1000)) {
console.log(payload.nbf, '>=', Math.floor(Date.now() / 1000));
if (payload.nbf > Math.floor(Date.now() / 1000)) {
return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
"description": "JSON Web Token implementation (symmetric and asymmetric)",
"main": "index.js",
"scripts": {
"test": "mocha"
"test": "mocha --require test/util/fakeDate"
},
"repository": {
"type": "git",
+14
View File
@@ -115,6 +115,20 @@ describe('RS256', function() {
});
});
it('should valid when date are equals', function(done) {
Date.fix(1451908031);
token = jwt.sign({ foo: 'bar' }, priv, { algorithm: 'RS256', notBefore: 0 });
jwt.verify(token, pub, function(err, decoded) {
assert.isNull(err);
assert.isNotNull(decoded);
Date.unfix();
done();
});
});
it('should NOT be invalid', function(done) {
// not active token
token = jwt.sign({ foo: 'bar' }, priv, { algorithm: 'RS256', notBeforeMinutes: 10 });
+32
View File
@@ -0,0 +1,32 @@
var oldDate = global.Date;
/*
* fix new Date() to a fixed unix timestamp.
*/
global.Date.fix = function (timestamp) {
var time = timestamp * 1000;
if (global.Date.unfake) {
global.Date.unfake();
}
global.Date = function (ts) {
return new oldDate(ts || time);
};
global.Date.prototype = Object.create(oldDate.prototype);
global.Date.prototype.constructor = global.Date;
global.Date.prototype.now = function () {
return time;
};
global.Date.now = function () {
return time;
};
global.Date.unfix = function () {
global.Date = oldDate;
};
};