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.
Simple JWT deocder
/**
* @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,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment