Published on April 3, 2024 · 6 min read

Using Base64 in JWT Authentication

Explore how Base64 encoding is used in JSON Web Tokens (JWT) for secure API authentication.

Understanding JWT Structure

JSON Web Tokens (JWT) consist of three parts separated by dots: header, payload, and signature. The header and payload are Base64Url encoded JSON objects, while the signature is created using a secret key and the encoded header and payload.

// JWT Structure
header.payload.signature

// Example JWT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Base64Url vs Standard Base64

JWTs use Base64Url encoding instead of standard Base64. The key differences are:

  • Replaces '+' with '-' in the encoding alphabet
  • Replaces '/' with '_' in the encoding alphabet
  • Removes padding '=' characters
  • Makes the token safe for URLs and HTTP headers

JWT Header and Payload

The header typically contains the token type and signing algorithm:

{
  "alg": "HS256",
  "typ": "JWT"
}

The payload contains the claims (data) you want to transmit:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Creating and Verifying JWTs

Here's how to create and verify JWTs in JavaScript:

// Creating a JWT
const header = base64UrlEncode(JSON.stringify({
  alg: 'HS256',
  typ: 'JWT'
}));

const payload = base64UrlEncode(JSON.stringify({
  sub: '1234567890',
  name: 'John Doe',
  iat: Math.floor(Date.now() / 1000)
}));

const signature = HMACSHA256(
  `${header}.${payload}`,
  'your-secret-key'
);

const jwt = `${header}.${payload}.${signature}`;

Security Best Practices

  • Always validate the signature before trusting the token
  • Use strong secret keys for signing
  • Include expiration times in your tokens
  • Don't store sensitive information in the payload
  • Use HTTPS to transmit tokens
  • Implement token revocation when needed

Common Pitfalls

  • Not validating the token signature
  • Using weak secret keys
  • Storing sensitive data in tokens
  • Not handling token expiration
  • Using tokens for long-term sessions