JWT (JSON Web Token) is a compact, secure way to transmit information between two parties — usually a client (like a browser or mobile app) and a server — as a JSON object. It’s commonly used for authentication and authorizationin web applications.
Codeflare
A JWT is made up of three parts, separated by dots (.):
xxxxx.yyyyy.zzzzz The header contains metadata about the token, like the type (JWT) and the algorithm used for signing (e.g., HS256).
{
"alg": "HS256",
"typ": "JWT"
} This is then Base64Url-encoded to form the first part of the token.
The payload contains the actual data (claims) you want to transmit, such as user info or token expiry time.
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"exp": 1739700000
} iss (issuer), exp (expiration), sub (subject), aud (audience).name, role.This part is also Base64Url-encoded.
To ensure the token wasn’t tampered with, the server signs it using a secret key (or a private key in asymmetric cryptography).
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
) The output is encoded again, forming the third part of the token.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ Authorization header:Authorization: Bearer <token> 6. Server verifies the token → If valid, grants access to protected routes/resources.
Using jsonwebtoken package:
const jwt = require('jsonwebtoken');
// Generate a token
const token = jwt.sign({ userId: 123, role: 'admin' }, 'secretkey', { expiresIn: '1h' });
// Verify a token
try {
const decoded = jwt.verify(token, 'secretkey');
console.log(decoded);
} catch (err) {
console.error('Invalid token');
} Latest tech news and coding tips.
The display property controls how an element behaves in the layout and how its children are arranged. Access software…
JavaScript is one of the most flexible programming languages ever created. That flexibility is powerful,…
What is Steam Locomotive (sl)? Steam Locomotive (sl) is a small terminal program on Unix/Linux systems…
What is Rate Limiting? Download this article as a PDF on the Codeflare Mobile App…
Learn on the Go. Download the Codeflare Mobile from iOS App Store. 1. What is…
Download the Codeflare iOS app and learn on the Go 1. What UI and UX…