JWT Authentication
In a RESTful architecture, the server should be stateless. This means we don't use server-side sessions. Instead, we use JWT (JSON Web Tokens).
1. What is a JWT?
A string representing encoded JSON that consists of three parts separated by dots:
Header.Payload.Signature
2. The Authentication Flow
- Client sends credentials (username/password) to
/login. - Server verifies and issues a signed JWT.
- Client stores the JWT (usually in
localStorage or a HttpOnly cookie). - Client sends the token in the
Authorization header for every subsequent request.
3. Authorization Header
The industry standard is the Bearer token scheme.
Authorization: Bearer <your_jwt_token>
4. Token Expiration & Refresh
Access tokens should be short-lived (e.g., 15 minutes). For a seamless user experience, use Refresh Tokens stored securely to generate new access tokens without re-logging.
Security Tip: Never store sensitive information like passwords or social security numbers in a JWT payload. Anyone can decode it (base64); it is only secure against tampering, not reading.