JWT Decoding Challenge

Understanding the Problem

JSON Web Tokens (JWTs) are like digital passports - they contain encoded information about the user. In this exercise, we need to:

Devising a Plan

  1. Identify the JWT structure (three parts separated by periods)
  2. Split the string using the period as a delimiter
  3. Decode the base64 encoded header and payload
  4. Parse the JSON to read the values
  5. Extract the required information

Basic Solution

File Location: index.js

// Given JWT string
const sampleJwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im15c2VsZkBhcHBhY2FkZW15LmlvIn0.EqRikwoGyAlfvblF_FdbnQlbAQGvWZlccFnmHOVdaLg";

// Step 1: Split the JWT into parts
const [header, payload, signature] = sampleJwt.split('.');
console.log('Parts:', { header, payload, signature });

// Step 2: Decode header and payload
const decodedHeader = Buffer.from(header, 'base64').toString();
const decodedPayload = Buffer.from(payload, 'base64').toString();

// Step 3: Parse the JSON
const headerObj = JSON.parse(decodedHeader);
const payloadObj = JSON.parse(decodedPayload);

console.log('Decoded Header:', headerObj);
console.log('Decoded Payload:', payloadObj);

// Extract required information
console.log('Algorithm:', headerObj.alg);
console.log('Email:', payloadObj.email);

Advanced Solution

Here's a more robust solution with error handling:

function decodeJWT(token) {
    try {
        // Validate input
        if (typeof token !== 'string') {
            throw new Error('JWT must be a string');
        }

        // Split and validate parts
        const parts = token.split('.');
        if (parts.length !== 3) {
            throw new Error('Invalid JWT format');
        }

        const [header, payload, signature] = parts;

        // Decode and parse parts
        const decoded = {
            header: JSON.parse(Buffer.from(header, 'base64').toString()),
            payload: JSON.parse(Buffer.from(payload, 'base64').toString()),
            signature
        };

        return {
            ...decoded,
            algorithm: decoded.header.alg,
            email: decoded.payload.email
        };
    } catch (error) {
        console.error('Error decoding JWT:', error.message);
        return null;
    }
}

const result = decodeJWT(sampleJwt);
console.log(result);

Expected Input/Output

Input:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im15c2VsZkBhcHBhY2FkZW15LmlvIn0.EqRikwoGyAlfvblF_FdbnQlbAQGvWZlccFnmHOVdaLg

Expected Output:

Algorithm: HS256
Email: myself@appacademy.io

Step by Step Explanation

  1. JWT Structure:
  2. Splitting the Token:
  3. Decoding:

Real World Applications

Understanding JWT structure and decoding is crucial for:

Common Mistakes to Avoid

Additional Tips

Further Learning

To deepen your understanding of JWTs: