Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an algorithm parameter to the decode method #16

Merged
merged 2 commits into from Apr 8, 2015
Merged
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: 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