From fd58e8961fe6034e7136ea0b31218a299ddf5178 Mon Sep 17 00:00:00 2001 From: "Johnny G. Halife" Date: Tue, 2 Aug 2016 04:35:34 -0300 Subject: [PATCH] Update middleware to throw when token is invalid when credentials aren't required --- lib/index.js | 2 +- test/jwt.test.js | 38 ++++++++++++++++++++++++++------------ 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/lib/index.js b/lib/index.js index 31946eed..732ace08 100644 --- a/lib/index.js +++ b/lib/index.js @@ -96,7 +96,7 @@ module.exports = function(options) { }, function verifyToken(secret, callback) { jwt.verify(token, secret, options, function(err, decoded) { - if (err && credentialsRequired) { + if (err) { callback(new UnauthorizedError('invalid_token', err)); } else { callback(null, decoded); diff --git a/test/jwt.test.js b/test/jwt.test.js index 62d05ebd..2d3a63dc 100644 --- a/test/jwt.test.js +++ b/test/jwt.test.js @@ -159,6 +159,32 @@ describe('failure tests', function () { }); }); + it('should throw error if token is expired even with when credentials are not required', function() { + var secret = 'shhhhhh'; + var token = jwt.sign({foo: 'bar', exp: 1382412921}, secret); + + req.headers = {}; + req.headers.authorization = 'Bearer ' + token; + expressjwt({ secret: secret, credentialsRequired: false })(req, res, function(err) { + assert.ok(err); + assert.equal(err.code, 'invalid_token'); + assert.equal(err.message, 'jwt expired'); + }); + }); + + it('should throw error if token is invalid even with when credentials are not required', function() { + var secret = 'shhhhhh'; + var token = jwt.sign({foo: 'bar', exp: 1382412921}, secret); + + req.headers = {}; + req.headers.authorization = 'Bearer ' + token; + expressjwt({ secret: "not the secret", credentialsRequired: false })(req, res, function(err) { + assert.ok(err); + assert.equal(err.code, 'invalid_token'); + assert.equal(err.message, 'invalid signature'); + }); + }); + }); describe('work tests', function () { @@ -216,18 +242,6 @@ describe('work tests', function () { }); }); - it('should work if token is expired and credentials are not required', function() { - var secret = 'shhhhhh'; - var token = jwt.sign({foo: 'bar', exp: 1382412921}, secret); - - req.headers = {}; - req.headers.authorization = 'Bearer ' + token; - expressjwt({ secret: secret, credentialsRequired: false })(req, res, function(err) { - assert(typeof err === 'undefined'); - assert(typeof req.user === 'undefined') - }); - }); - it('should not work if no authorization header', function() { req = {}; expressjwt({ secret: 'shhhh' })(req, res, function(err) {