JWT Basics
JSON Web Tokens structure, creation, and validation.
JWT Structure
# JWT format
header.payload.signature
# Example
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9obiJ9.abc123
# Parts
Header # algorithm and token type
Payload # claims (data)
Signature # verification
Header
{
"alg": "HS256",
"typ": "JWT"
}
# Common algorithms
HS256 # HMAC with SHA-256
RS256 # RSA with SHA-256
ES256 # ECDSA with SHA-256
Payload Claims
# Registered claims
iss # issuer
sub # subject (user ID)
aud # audience
exp # expiration time
iat # issued at
nbf # not before
# Custom claims
userId: 123
role: admin
Node.js Example
# Create token
const jwt = require("jsonwebtoken");
const token = jwt.sign(
{ userId: 123 },
"secret-key",
{ expiresIn: "1h" }
);
# Verify token
const decoded = jwt.verify(token, "secret-key");
Usage in HTTP
# Send token in header
Authorization: Bearer eyJhbGci...
# Extract in Node.js
const token = req.headers.authorization.split(" ")[1];