Is it possible to decode a JWT token using the inline task?

I’ve created a simple javascript function to decode a JWT token, however it fails to execute, returning the following error: “Error evaluating the script ReferenceError: atob is not defined at line 13”

( function() {
  // Split the JWT into its three parts (header, payload, and signature)
  const token = $.jwt
  const parts = token.split('.');

  // Validate the format of the JWT
  if (parts.length !== 3) {
    throw new Error('Invalid JWT format');
  }

  // Decode the payload (the second part of the JWT)
  const base64Payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');  // Handle Base64 URL encoding
  const decodedPayload = atob(base64Payload);  // Use atob for base64 decoding

  // Parse the payload as JSON
  const parsedPayload = JSON.parse(decodedPayload);

  return parsedPayload;
})();
1 Like

Shoutout to Yong for a nifty solution:

(() => {
    const parts = $.jwt.split('.');
    if (parts.length !== 3) {
        throw new Error('Invalid JWT format');
    }
    const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
    const paddedBase64 = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, '=');
    const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    let binaryString = '';
    for (let i = 0; i < paddedBase64.length; i += 4) {
        const chunk =
            (base64Chars.indexOf(paddedBase64[i]) << 18) |
            (base64Chars.indexOf(paddedBase64[i + 1]) << 12) |
            ((base64Chars.indexOf(paddedBase64[i + 2]) || 0) << 6) |
            (base64Chars.indexOf(paddedBase64[i + 3]) || 0);
        binaryString += String.fromCharCode((chunk >> 16) & 0xff);
        if (paddedBase64[i + 2] !== '=') {
            binaryString += String.fromCharCode((chunk >> 8) & 0xff);
        }
        if (paddedBase64[i + 3] !== '=') {
            binaryString += String.fromCharCode(chunk & 0xff);
        }
    }
    return JSON.parse(binaryString);
})();
1 Like

Thanks for sharing @simon.marles :sunglasses: