From 02d24b6709b6a50d13696f2da61f5f864b0b9b8d Mon Sep 17 00:00:00 2001 From: Alaister Young Date: Tue, 1 Mar 2022 10:21:32 +1100 Subject: [PATCH] Add support for JWT header --- index.d.ts | 1 + index.js | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/index.d.ts b/index.d.ts index 30cf1ea..25f4fdc 100644 --- a/index.d.ts +++ b/index.d.ts @@ -42,6 +42,7 @@ type JWTAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | type JWTSignOptions = { algorithm?: JWTAlgorithm, keyid?: string + header?: object } type JWTVerifyOptions = { diff --git a/index.js b/index.js index 66e73b2..ddd2924 100644 --- a/index.js +++ b/index.js @@ -53,9 +53,9 @@ class JWT { return null } } - async sign(payload, secret, options = { algorithm: 'HS256' }) { + async sign(payload, secret, options = { algorithm: 'HS256', header: { typ: 'JWT' } }) { if (typeof options === 'string') - options = { algorithm: options } + options = { algorithm: options, header: { typ: 'JWT' } } if (payload === null || typeof payload !== 'object') throw new Error('payload must be an object') if (typeof secret !== 'string') @@ -67,7 +67,7 @@ class JWT { throw new Error('algorithm not found') payload.iat = Math.floor(Date.now() / 1000) const payloadAsJSON = JSON.stringify(payload) - const partialToken = `${Base64URL.stringify(this._utf8ToUint8Array(JSON.stringify({ alg: options.algorithm, kid: options.keyid })))}.${Base64URL.stringify(this._utf8ToUint8Array(payloadAsJSON))}` + const partialToken = `${Base64URL.stringify(this._utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm, kid: options.keyid })))}.${Base64URL.stringify(this._utf8ToUint8Array(payloadAsJSON))}` let keyFormat = 'raw' let keyData if (secret.startsWith('-----BEGIN')) {