Skip to content

Commit

Permalink
Merge pull request #38 from alexjab/feature/exp_nbf_claims
Browse files Browse the repository at this point in the history
Add support for nbf and exp claims
  • Loading branch information
hokaccha committed Mar 11, 2016
2 parents c9fd642 + cd0e4e3 commit c9a52bb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ jwt.decode = function jwt_decode(token, key, noVerify, algorithm) {
throw new Error('Algorithm not supported');
}

// Support for nbf and exp claims.
// According to the RFC, they should be in seconds.
if (payload.nbf && Date.now() < payload.nbf*1000) {
throw new Error('Token not yet active');
}

if (payload.exp && Date.now() > payload.exp*1000) {
throw new Error('Token expired');
}

// verify signature. `sign` will return base64 string.
var signingInput = [headerSeg, payloadSeg].join('.');
if (!verify(signingInput, key, signingMethod, signingType, signatureSeg)) {
Expand Down
14 changes: 14 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ describe('decode', function() {
expect(fn).to.throwError(/Signature verification failed/);
});

it('throw an error when the token is not yet active (optional nbf claim)', function() {
var nbf = (Date.now() + 1000) / 1000;
var token = jwt.encode({ foo: 'bar', nbf: nbf }, key);
var fn = jwt.decode.bind(null, token, key);
expect(fn).to.throwError(/Token not yet active/);
});

it('throw an error when the token has expired (optional exp claim)', function() {
var exp = (Date.now() - 1000) / 1000;
var token = jwt.encode({ foo: 'bar', exp: exp }, key);
var fn = jwt.decode.bind(null, token, key);
expect(fn).to.throwError(/Token expired/);
});

it('do not throw any error when verification is disabled', function() {
var obj = { foo: 'bar' };
var key = 'key';
Expand Down

0 comments on commit c9a52bb

Please sign in to comment.