From 957957cfa44474049b4603b293569588ee9ffd97 Mon Sep 17 00:00:00 2001 From: Greg Date: Tue, 7 Apr 2015 11:01:00 +0100 Subject: [PATCH] Add an algorithm paramter to the decode method so that it overrides the alg property in the token and verifies on the fly --- .gitignore | 1 + lib/jwt.js | 13 +++++++------ test/basic.js | 10 ++++++++++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 3c3629e..7a1537b 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +.idea node_modules diff --git a/lib/jwt.js b/lib/jwt.js index f381265..bd2ce9b 100644 --- a/lib/jwt.js +++ b/lib/jwt.js @@ -50,11 +50,12 @@ jwt.version = '0.2.0'; * * @param {Object} token * @param {String} key - * @param {Boolean} noVerify + * @param {Boolean} noVerify + * @param {String} algorithm * @return {Object} payload * @api public */ -jwt.decode = function jwt_decode(token, key, noVerify) { +jwt.decode = function jwt_decode(token, key, noVerify, algorithm) { // check seguments var segments = token.split('.'); if (segments.length !== 3) { @@ -71,8 +72,8 @@ jwt.decode = function jwt_decode(token, key, noVerify) { var payload = JSON.parse(base64urlDecode(payloadSeg)); if (!noVerify) { - var signingMethod = algorithmMap[header.alg]; - var signingType = typeMap[header.alg]; + var signingMethod = algorithmMap[algorithm || header.alg]; + var signingType = typeMap[algorithm || header.alg]; if (!signingMethod || !signingType) { throw new Error('Algorithm not supported'); } @@ -124,7 +125,7 @@ jwt.encode = function jwt_encode(payload, key, algorithm) { segments.push(sign(segments.join('.'), key, signingMethod, signingType)); return segments.join('.'); -} +}; /** @@ -165,7 +166,7 @@ function base64urlDecode(str) { } function base64urlUnescape(str) { - str += Array(5 - str.length % 4).join('='); + str += new Array(5 - str.length % 4).join('='); return str.replace(/\-/g, '+').replace(/_/g, '/'); } diff --git a/test/basic.js b/test/basic.js index 523d4ec..5cd9f2f 100644 --- a/test/basic.js +++ b/test/basic.js @@ -44,6 +44,16 @@ describe('encode and decode', function() { expect(fn2()).to.eql(obj); }); + it('decode token given algorithm', function() { + var obj = { foo: 'bar' }; + var key = 'key'; + var token = jwt.encode(obj, key, 'HS512'); + var obj2 = jwt.decode(token, key, false, 'HS512'); + expect(obj2).to.eql(obj); + expect(jwt.decode.bind(null, token, key, false, 'HS256')).to.throwException(); + expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwException(); + }); + it('RS256', function() { var obj = { foo: 'bar' }; var pem = fs.readFileSync(__dirname + '/test.pem').toString('ascii');