Skip to content

Commit 957957c

Browse files
author
Greg
committed
Add an algorithm paramter to the decode method so that it overrides the alg property in the token and verifies on the fly
1 parent a2a14d0 commit 957957c

3 files changed

Lines changed: 18 additions & 6 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
.idea
12
node_modules

lib/jwt.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,12 @@ jwt.version = '0.2.0';
5050
*
5151
* @param {Object} token
5252
* @param {String} key
53-
* @param {Boolean} noVerify
53+
* @param {Boolean} noVerify
54+
* @param {String} algorithm
5455
* @return {Object} payload
5556
* @api public
5657
*/
57-
jwt.decode = function jwt_decode(token, key, noVerify) {
58+
jwt.decode = function jwt_decode(token, key, noVerify, algorithm) {
5859
// check seguments
5960
var segments = token.split('.');
6061
if (segments.length !== 3) {
@@ -71,8 +72,8 @@ jwt.decode = function jwt_decode(token, key, noVerify) {
7172
var payload = JSON.parse(base64urlDecode(payloadSeg));
7273

7374
if (!noVerify) {
74-
var signingMethod = algorithmMap[header.alg];
75-
var signingType = typeMap[header.alg];
75+
var signingMethod = algorithmMap[algorithm || header.alg];
76+
var signingType = typeMap[algorithm || header.alg];
7677
if (!signingMethod || !signingType) {
7778
throw new Error('Algorithm not supported');
7879
}
@@ -124,7 +125,7 @@ jwt.encode = function jwt_encode(payload, key, algorithm) {
124125
segments.push(sign(segments.join('.'), key, signingMethod, signingType));
125126

126127
return segments.join('.');
127-
}
128+
};
128129

129130

130131
/**
@@ -165,7 +166,7 @@ function base64urlDecode(str) {
165166
}
166167

167168
function base64urlUnescape(str) {
168-
str += Array(5 - str.length % 4).join('=');
169+
str += new Array(5 - str.length % 4).join('=');
169170
return str.replace(/\-/g, '+').replace(/_/g, '/');
170171
}
171172

test/basic.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,16 @@ describe('encode and decode', function() {
4444
expect(fn2()).to.eql(obj);
4545
});
4646

47+
it('decode token given algorithm', function() {
48+
var obj = { foo: 'bar' };
49+
var key = 'key';
50+
var token = jwt.encode(obj, key, 'HS512');
51+
var obj2 = jwt.decode(token, key, false, 'HS512');
52+
expect(obj2).to.eql(obj);
53+
expect(jwt.decode.bind(null, token, key, false, 'HS256')).to.throwException();
54+
expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwException();
55+
});
56+
4757
it('RS256', function() {
4858
var obj = { foo: 'bar' };
4959
var pem = fs.readFileSync(__dirname + '/test.pem').toString('ascii');

0 commit comments

Comments
 (0)