Skip to main content
Web DevAuth & SecurityDiagramIntermediate

JWT

KO: JWT·EN: JWT·JA: JWT·JSON Web Token

A compact, self-contained token standard (RFC 7519) that carries digitally signed JSON claims for stateless authentication and authorization

Table of Contents

Structure Diagram

JWT Structure (Header · Payload · Signature) & VerificationTap a node
Base64UrlBase64UrlValid SigMismatchHeader (a…Payload (…HMAC / RS…Stateless…Tampered …
ROOTHeader (alg, typ)
1 link
Quick Answer

What is JWT?

A compact, self-contained token standard (RFC 7519) that carries digitally signed JSON claims for stateless authentication and authorization. It is a core concept in Auth & Security within Web Dev.

Core Principles

A JWT (JSON Web Token, RFC 7519) is a dot-separated string composed of three Base64Url-encoded segments: Header.Payload.Signature.

  • Header: Declares the token type (JWT) and signing algorithm (HS256, RS256, ES256).
  • Payload: Holds claims such as subject ID (sub), roles, issuer (iss), and expiration timestamp (exp).
  • Signature: Cryptographically signs the encoded header and payload using a shared secret or asymmetric private key.

When a client sends Authorization: Bearer <token>, any backend service can verify authenticity and expiration mathematically—without querying a central session database on every request.

Practical Takeaways

  • Signed does not mean encrypted: Anyone can Base64Url-decode a JWT payload. Never store passwords, secrets, or sensitive PII inside claims.
  • Pair short-lived Access Tokens with rotating Refresh Tokens: Because stateless JWTs cannot be easily revoked before expiry, keep access tokens short (5–15 minutes) and issue revocable, single-use refresh tokens stored in HttpOnly, Secure cookies.
  • Hard-code allowed algorithms and protect storage: Storing JWTs in localStorage exposes them to XSS theft; prefer HttpOnly cookies for web apps. Always pin expected verification algorithms server-side to block alg: "none" and key-confusion attacks.

Notable Examples

  • OpenID Connect (OIDC) & OAuth 2.0: Standard format for identity tokens issued by Google, Apple, Auth0, and Clerk.
  • Microservice authorization: Downstream services independently verify tokens against a public JWKS endpoint without bottlenecking a shared session store.
  • Mobile & multi-region APIs: Clean stateless authentication across distributed edge servers and native clients.

Practical Code Snippet

Copy and drop straight into your project
jwt-auth.tsTypeScript
import { SignJWT, jwtVerify } from "jose"; const secret = new TextEncoder().encode(process.env.JWT_SECRET); export async function createAccessToken(userId: string) {  return new SignJWT({ sub: userId, role: "member" })    .setProtectedHeader({ alg: "HS256" })    .setIssuedAt()    .setExpirationTime("15m")    .sign(secret);} export async function verifyAccessToken(token: string) {  const { payload } = await jwtVerify(token, secret);  return payload;}