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

When decoding, if JWT payload is not valid it returns null #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
10 changes: 6 additions & 4 deletions lib/verify-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ function isObject(thing) {
return Object.prototype.toString.call(thing) === '[object Object]';
}

function safeJsonParse(thing) {
function safeJsonParse(thing, encoding) {
if (isObject(thing))
return thing;
try { return JSON.parse(thing); }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not supported by the JSON.parse API, see comment here: #86 (comment)

Ref: reviver in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO only the if (!payload) { return null; } check should be added by this CR, encoding support is addressed in newer CR #86

try { return JSON.parse(thing, encoding); }
catch (e) { return undefined; }
}

Expand Down Expand Up @@ -67,8 +67,10 @@ function jwsDecode(jwsSig, opts) {
return null;

var payload = payloadFromJWS(jwsSig);
if (header.typ === 'JWT' || opts.json)
payload = JSON.parse(payload, opts.encoding);
if (header.typ === 'JWT' || opts.json){
payload = safeJsonParse(payload, opts.encoding);
if (!payload) { return null; }
}

return {
header: header,
Expand Down
7 changes: 3 additions & 4 deletions test/jws.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ if (SUPPORTS_ENCRYPTED_KEYS) {
test('jws.decode: not a jws signature', function (t) {
t.same(jws.decode('some garbage string'), null);
t.same(jws.decode('http://sub.domain.org'), null);
t.same(jws.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e3.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'), null);
t.end();
});

Expand All @@ -295,10 +296,8 @@ test('jws.decode: with invalid json in body', function (t) {
const header = Buffer('{"alg":"HS256","typ":"JWT"}').toString('base64');
const payload = Buffer('sup').toString('base64');
const sig = header + '.' + payload + '.';
var parts;
t.throws(function () {
parts = jws.decode(sig);
})
const parts = jws.decode(sig);
t.same(parts, null);
t.end();
});

Expand Down