This JavaScript function allows you to decode a JSON Web Token (JWT) by splitting it into its three parts (header, payload, and signature) and decoding the base64-encoded strings. It returns an object containing the decoded header, payload, and signature.
/**
* Decode a JSON Web Token (JWT) and retrieve its header, payload, and signature.
* @param {string} jwt - The JSON Web Token to decode.
* @returns {Object} - An object containing the decoded header, payload, and signature.
*/
function decodeJWT(jwt) {
try {
const parts = jwt.split(".");
// Decode the base64 encoded strings
const header = JSON.parse(atob(parts[0]));
const payload = JSON.parse(atob(parts[1]));
const signature = parts[2];
return {
header: header,
payload: payload,
signature: signature,
};
} catch (error) {
console.error('Error decoding string:', error);
}
}
Please note that this function assumes the input JWT is properly formatted and consists of three dot-separated parts. It catches any errors that occur during the decoding process and logs them to the console.