Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created June 14, 2023 08:34
Show Gist options
  • Save tobiashm/e89c81f26c8a165d9fbfc92e3c9afb79 to your computer and use it in GitHub Desktop.
Save tobiashm/e89c81f26c8a165d9fbfc92e3c9afb79 to your computer and use it in GitHub Desktop.

Revisions

  1. tobiashm created this gist Jun 14, 2023.
    32 changes: 32 additions & 0 deletions decode-jwt.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    /**
    * @typedef {object} Header - JOSE Header https://datatracker.ietf.org/doc/html/rfc7519#section-5
    * @property {string} typ - Type https://datatracker.ietf.org/doc/html/rfc7519#section-5.1
    * @property {string} alg - Algorithm https://datatracker.ietf.org/doc/html/rfc7515#section-4.1.1
    */

    /**
    * @param {string} char - a string containing a single character
    */
    const toURIComponent = (char) => '%' + ('00' + char.charCodeAt(0).toString(16)).slice(-2);

    /**
    * @template T
    * @param {string} part - The encoded header or payload part of the JWT to decode
    * @returns {T} - object containing the payload of the JWT
    */
    const decodeJWTPart = (part) =>
    JSON.parse(decodeURIComponent(Array.from(window.atob(part)).map(toURIComponent).join('')));

    /**
    * @template T - The payload type
    * @param {string} jwt - The JWT to decode
    * @returns {{ header: Header, payload: T, signature: string }}
    */
    export function decodeJWT(jwt) {
    const [encodedHeader, encodedPayload, signature] = jwt.split('.');
    return {
    header: decodeJWTPart(encodedHeader),
    payload: decodeJWTPart(encodedPayload),
    signature,
    };
    }