Skip to content

Commit

Permalink
Add an algorithm paramter to the decode method so that it overrides t…
Browse files Browse the repository at this point in the history
…he alg property in the token and verifies on the fly
  • Loading branch information
Greg committed Apr 7, 2015
1 parent a2a14d0 commit 957957c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea
node_modules
13 changes: 7 additions & 6 deletions lib/jwt.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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');
}
Expand Down Expand Up @@ -124,7 +125,7 @@ jwt.encode = function jwt_encode(payload, key, algorithm) {
segments.push(sign(segments.join('.'), key, signingMethod, signingType));

return segments.join('.');
}
};


/**
Expand Down Expand Up @@ -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, '/');
}

Expand Down
10 changes: 10 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit 957957c

Please sign in to comment.