From 9fcaf1170ebf3a2e58498c263c2af5c8b9bcb2b8 Mon Sep 17 00:00:00 2001 From: dschenkelman Date: Tue, 2 Jun 2015 00:06:16 -0300 Subject: [PATCH] When decoding, if JWT payload is not valid it returns null --- lib/verify-stream.js | 10 ++++++---- test/jws.test.js | 7 +++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/verify-stream.js b/lib/verify-stream.js index d9bfa2b..44ed594 100644 --- a/lib/verify-stream.js +++ b/lib/verify-stream.js @@ -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); } + try { return JSON.parse(thing, encoding); } catch (e) { return undefined; } } @@ -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, diff --git a/test/jws.test.js b/test/jws.test.js index 063969b..4ff2f82 100644 --- a/test/jws.test.js +++ b/test/jws.test.js @@ -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(); }); @@ -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(); });