π Authentication & Authorization β
Verifying identity and controlling access.
Authentication vs Authorization β
- Authentication (AuthN) β Who are you? (identity)
- Authorization (AuthZ) β What can you do? (permissions)
Authentication methods β
JWT (JSON Web Token) β
Client β Login β Server returns JWT
Client β Request + JWT in header β Server validates JWT- Stateless β no server-side session
- Contains claims (user ID, roles, expiry)
- Short-lived access token (15min) + long-lived refresh token (7 days)
- Store in httpOnly cookie (not localStorage)
Session-based β
Client β Login β Server creates session, returns cookie
Client β Request + cookie β Server looks up session- Stateful β session stored server-side (Redis)
- Easier to revoke than JWT
- Better for traditional web apps
OAuth2 / OpenID Connect β
- Delegate authentication to a provider (Google, GitHub)
- Use for "Sign in with..." flows
- Authorization Code flow for server apps
- PKCE flow for SPAs and mobile
Authorization models β
RBAC (Role-Based) β
User β has Role β Role has Permissions
Admin β can: create, read, update, delete
Editor β can: read, update
Viewer β can: readABAC (Attribute-Based) β
Allow if: user.department === resource.department AND user.level >= 3More flexible, more complex.
Security checklist β
- [ ] Hash passwords with bcrypt/argon2
- [ ] Rate limit login attempts
- [ ] Implement account lockout after N failures
- [ ] Use HTTPS everywhere
- [ ] Validate tokens server-side on every request
- [ ] Implement CSRF protection for cookie-based auth
- [ ] Log authentication events (login, logout, failures)
- [ ] Support MFA for sensitive operations