Jwt in authentication

JWT (JSON Web Token) is a compact, self-contained token for securely transmitting information. It has three parts: Header (algorithm), Payload (claims/data), and Signature (verification). Used for stateless authentication.

Example

// JWT structure: header.payload.signature
// Header: { "alg": "HS256", "typ": "JWT" }
// Payload: { "userId": "123", "role": "admin", "exp": 1234567890 }

const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: '123' }, 'secret', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secret');

jwt.sign creates a token with payload and expiry, jwt.verify decodes and validates it.