Web Security: JWT & OAuth 2.0
Authentication mechanisms explained: JWT structure and security best practices, OAuth 2.0 flows, and OpenID Connect.
Authentication vs Authorization
- Authentication (AuthN): Who are you?
- Verifying identity (Login, Password, 2FA).
- Failure:
401 Unauthorized.
- Authorization (AuthZ): What are you allowed to do?
- Verifying permissions (Admin, Editor, Viewer).
- Failure:
403 Forbidden.
JWT (JSON Web Tokens)
A compact, URL-safe means of representing claims to be transferred between two parties. Stateless Authentication: The server doesn't need to store session data. The token is the proof.
Structure (Header.Payload.Signature)
- Header: Algorithm and Type.
{"alg": "HS256", "typ": "JWT"} - Payload (Claims): Data (User ID, Role, Expiration). NOT ENCRYPTED (Base64 encoded only).
{"sub": "123", "role": "admin", "iat": 1516239022} - Signature: Verifies integrity.
HMACSHA256(base64(header) + "." + base64(payload), SECRET_KEY)
Pros & Cons
- Pros:
- Scalable: Good for Microservices (Authentication Service issues token, other services just verify signature).
- SSO: Easy to implement Single Sign-On.
- Cons:
- Revocation: Hard to ban a user instantly (token is valid until expiry).
- Size: larger than session cookies.
Security Best Practices
- Never store sensitive data (passwords) in Payload.
- Short Lifespan: Access Tokens should live short (e.g., 15 mins).
- Refresh Tokens: Use long-lived Refresh Tokens to get new Access Tokens.
- HTTPS: Always transmit over HTTPS to prevent interception.
OAuth 2.0 (Open Authorization)
A standard for delegated authorization. Analogy: Giving a hotel valet your "Valet Key" (Access Token) allows them to park your car (Resource), but not open the trunk or glovebox (Scope).
Roles
- Resource Owner: The User.
- Client: The App (e.g., Spotify).
- Authorization Server: The Identity Provider (e.g., Facebook).
- Resource Server: The API holding data (e.g., Facebook API).
The Flow (Authorization Code)
- User clicks "Login with Facebook".
- User is redirected to Facebook.
- User logs in and Consents to scopes (e.g., "Read Friends List").
- Facebook redirects back to Spotify with a temporary Code.
- Spotify exchanges the Code + Client Secret for an Access Token.
- Spotify uses Access Token to fetch data.
OIDC (OpenID Connect)
A layer on top of OAuth 2.0 for Authentication.
- OAuth 2.0 is for Authorization (Access).
- OIDC adds an ID Token (JWT) to identifying Who the user is.