Skip to content

Commit

Permalink
Merge pull request #16 from GrumpyWizards/master
Browse files Browse the repository at this point in the history
Add an algorithm parameter to the decode method
  • Loading branch information
hokaccha committed Apr 8, 2015
2 parents a2a14d0 + ef2d635 commit ecf908a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
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 ecf908a

Please sign in to comment.