From 6ccc56962112a3939bfea2852d1907dc382d66db Mon Sep 17 00:00:00 2001 From: Jarrad Whitaker Date: Fri, 6 Oct 2017 17:17:37 +1100 Subject: [PATCH] add capacity to decode by header-specified kid --- README.md | 13 ++++++++++++- lib/jwt.js | 6 +++++- test/basic.js | 8 ++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c694654..53334a0 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ console.log(decoded); //=> { foo: 'bar' } ```javascript /* - * jwt.decode(token, key, noVerify, algorithm) + * jwt.decode(token, keyOrKeys, noVerify, algorithm) */ // decode, by default the signature of the token is verified @@ -44,6 +44,17 @@ console.log(decoded); //=> { foo: 'bar' } // decode with a specific algorithm (not using the algorithm described in the token payload) var decoded = jwt.decode(token, secret, false, 'HS256'); console.log(decoded); //=> { foo: 'bar' } + +// decode when the token specifies a key id, +// e.g. token header contains { kid: 'keyId1' } +// and was encrypted with the key for 'secret'. +var keys = { + keyId1: secret, + keyId2: someOtherSecret + //.. +} +var decoded = jwt.decode(token, keys); +console.log(decoded); //=> { foo: 'bar' } ``` ### Algorithms diff --git a/lib/jwt.js b/lib/jwt.js index 204ce8d..688b798 100644 --- a/lib/jwt.js +++ b/lib/jwt.js @@ -82,6 +82,10 @@ jwt.decode = function jwt_decode(token, key, noVerify, algorithm) { throw new Error('Algorithm not supported'); } + if (key[header.kid]) { + key = key[header.kid]; + } + // verify signature. `sign` will return base64 string. var signingInput = [headerSeg, payloadSeg].join('.'); if (!verify(signingInput, key, signingMethod, signingType, signatureSeg)) { @@ -107,7 +111,7 @@ jwt.decode = function jwt_decode(token, key, noVerify, algorithm) { * Encode jwt * * @param {Object} payload - * @param {String} key + * @param {String|{[kid: String]: String}} key * @param {String} algorithm * @param {Object} options * @return {String} token diff --git a/test/basic.js b/test/basic.js index 99ee165..a6f9b6f 100644 --- a/test/basic.js +++ b/test/basic.js @@ -132,6 +132,14 @@ describe('decode', function() { var obj2 = jwt.decode(token, cert); expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwError(); }); + + it('decode token when header specifies a kid', function() { + var token = jwt.encode(obj, pem, alg, {header: {kid: 'myKey'}}); + var obj2 = jwt.decode(token, {myKey:cert}); + expect(obj2).to.eql(obj); + expect(jwt.decode.bind(null, token, {notMyKey:cert})).to.throwError(); + expect(jwt.decode.bind(null, token, {myKey:'invalid_key'})).to.throwError(); + }) }); });