Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 5 additions & 1 deletion lib/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
})
});
});

Expand Down