Skip to content

Commit 9fcaf11

Browse files
committed
When decoding, if JWT payload is not valid it returns null
1 parent c2f94b0 commit 9fcaf11

2 files changed

Lines changed: 9 additions & 8 deletions

File tree

lib/verify-stream.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ function isObject(thing) {
1111
return Object.prototype.toString.call(thing) === '[object Object]';
1212
}
1313

14-
function safeJsonParse(thing) {
14+
function safeJsonParse(thing, encoding) {
1515
if (isObject(thing))
1616
return thing;
17-
try { return JSON.parse(thing); }
17+
try { return JSON.parse(thing, encoding); }
1818
catch (e) { return undefined; }
1919
}
2020

@@ -67,8 +67,10 @@ function jwsDecode(jwsSig, opts) {
6767
return null;
6868

6969
var payload = payloadFromJWS(jwsSig);
70-
if (header.typ === 'JWT' || opts.json)
71-
payload = JSON.parse(payload, opts.encoding);
70+
if (header.typ === 'JWT' || opts.json){
71+
payload = safeJsonParse(payload, opts.encoding);
72+
if (!payload) { return null; }
73+
}
7274

7375
return {
7476
header: header,

test/jws.test.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ if (SUPPORTS_ENCRYPTED_KEYS) {
279279
test('jws.decode: not a jws signature', function (t) {
280280
t.same(jws.decode('some garbage string'), null);
281281
t.same(jws.decode('http://sub.domain.org'), null);
282+
t.same(jws.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e3.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M'), null);
282283
t.end();
283284
});
284285

@@ -295,10 +296,8 @@ test('jws.decode: with invalid json in body', function (t) {
295296
const header = Buffer('{"alg":"HS256","typ":"JWT"}').toString('base64');
296297
const payload = Buffer('sup').toString('base64');
297298
const sig = header + '.' + payload + '.';
298-
var parts;
299-
t.throws(function () {
300-
parts = jws.decode(sig);
301-
})
299+
const parts = jws.decode(sig);
300+
t.same(parts, null);
302301
t.end();
303302
});
304303

0 commit comments

Comments
 (0)