diff --git a/lib/index.js b/lib/index.js index 1b5b498..2ab7a00 100644 --- a/lib/index.js +++ b/lib/index.js @@ -27,7 +27,7 @@ internals.implementation = function (server, options) { return { authenticate: function (request, reply) { var token = extract(request, options); - + if (!token && request.auth.mode === 'optional') { return reply.continue({ credentials: {} }); } @@ -41,7 +41,17 @@ internals.implementation = function (server, options) { } var keyFunc = (internals.isFunction(options.key)) ? options.key : function (decoded, callback) { callback(null, options.key); }; - keyFunc(JWT.decode(token), function (err, key, extraInfo) { + + var decoded; + try { + decoded = JWT.decode(token); + } + catch(e) + { + return reply(Boom.unauthorized('Invalid token format', 'Token')); + } + + keyFunc(decoded, function (err, key, extraInfo) { if (err) { return reply(Boom.wrap(err)); } diff --git a/test/test.js b/test/test.js index e72cddf..37edd62 100644 --- a/test/test.js +++ b/test/test.js @@ -61,6 +61,29 @@ test("Malformed JWT", function(t) { }); }); +test("Try using a token with missing characters in body", function(t) { + // use the token as the 'authorization' header in requests + var token = JWT.sign({ id:123,"name":"Charlie" }, secret); + // delete some characters in body + var tokenData = token.split('.'); + var header = tokenData[0], + body = tokenData[1], + signature = tokenData[2]; + token = header + '.' + body.substring(0, body.length - 1) + '.' + signature; + /*console.log(" - - - - - - token - - - - -"); + console.log(token);*/ + var options = { + method: "POST", + url: "/privado", + headers: { authorization: "Bearer "+token } + }; + // server.inject lets us similate an http request + server.inject(options, function(response) { + t.equal(response.statusCode, 401, "INVALID Token should fail"); + t.end(); + }); +}); + test("Try using an incorrect secret to sign the JWT", function(t) { // use the token as the 'authorization' header in requests var token = JWT.sign({ id:123,"name":"Charlie" }, 'incorrectSecret');