Bearer Tokens

Token-based authentication with JWT

Bearer token authentication sends a token in the Authorization header. The token is typically a JWT (JSON Web Token) obtained by logging in.

Unlike Basic Auth, you don't send credentials with every request — just the token. The server validates the token to identify the user.

Making Authenticated Requests

async function fetchWithToken(url, token, options = {}) { const response = await fetch(url, { ...options, headers: { ...options.headers, 'Authorization': `Bearer ${token}` } }); if (response.status === 401) { // Token expired or invalid throw new Error('Unauthorized - token may be expired'); } return response; } // Usage const token = localStorage.getItem('authToken'); const response = await fetchWithToken('/api/profile', token);

Login Flow

async function login(email, password) { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); if (!response.ok) { throw new Error('Login failed'); } const { accessToken, refreshToken } = await response.json(); // Store tokens (consider security implications) localStorage.setItem('accessToken', accessToken); localStorage.setItem('refreshToken', refreshToken); return { accessToken, refreshToken }; }

Token Refresh

async function refreshAccessToken() { const refreshToken = localStorage.getItem('refreshToken'); const response = await fetch('/api/auth/refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken }) }); if (!response.ok) { // Refresh token expired - user must log in again localStorage.removeItem('accessToken'); localStorage.removeItem('refreshToken'); throw new Error('Session expired'); } const { accessToken } = await response.json(); localStorage.setItem('accessToken', accessToken); return accessToken; } // Auto-refresh on 401 async function fetchWithAutoRefresh(url, options = {}) { let token = localStorage.getItem('accessToken'); let response = await fetchWithToken(url, token, options); if (response.status === 401) { // Try to refresh the token token = await refreshAccessToken(); response = await fetchWithToken(url, token, options); } return response; }

JWT Decoder

Paste a JWT above to see its decoded contents

JWT Structure

A JWT has three parts separated by dots:

  • Header - Algorithm and token type
  • Payload - Claims (user data, expiration, etc.)
  • Signature - Verifies the token wasn't tampered with

The payload is Base64-encoded, not encrypted. Don't store sensitive data in it.