Implementing Authentication Mechanisms
1. Designing User Authentication Flow
Client ── POST /login (creds) ──> Server
←── 200 + tokens (access + refresh) ──
Client ── GET /api (Bearer access) ──> Server
← validates JWT, returns data ─
On expiry:
Client ── POST /refresh (refresh) ──> Server
← new access token ─
2. Implementing JWT Generation and Validation
Example: Generate and verify (jjwt)
String token = Jwts.builder()
.subject(userId.toString())
.issuer("acme")
.issuedAt(new Date())
.expiration(Date.from(Instant.now().plus(15, MINUTES)))
.claim("roles", List.of("ADMIN"))
.signWith(secretKey, Jwts.SIG.HS256)
.compact();
Jws<Claims> jws = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token);
String sub = jws.getPayload().getSubject();
Warning: Never use the unsafe
none algorithm; always pin algorithm and verify iss, aud, exp.3. Implementing Session Management
| Aspect | Detail |
|---|---|
| Storage | Server-side (Redis), HTTP-only cookie holds ID |
| Cookie flags | HttpOnly; Secure; SameSite=Lax |
| Idle timeout | 30 min default |
| Absolute timeout | 8-12h max |
| Rotate on auth events | Prevent fixation |
4. Implementing OAuth 2.0 Client
| Flow | Use |
|---|---|
| Authorization Code + PKCE | Web/mobile/SPA (recommended) |
| Client Credentials | Service-to-service |
| Device Code | Input-constrained devices |
| Implicit | DEPRECATED |
| Resource Owner Password | DEPRECATED |
5. Designing Password Storage
| Algorithm | Recommendation |
|---|---|
| Argon2id | Preferred for new systems |
| bcrypt | Acceptable; use cost ≥ 12 |
| scrypt | Acceptable; memory-hard |
| PBKDF2 | Use ≥ 600k iterations (SHA-256) |
| MD5/SHA-1/plain | NEVER |
Example: Spring Security PasswordEncoder
PasswordEncoder enc = new BCryptPasswordEncoder(12);
String hash = enc.encode(plain);
boolean ok = enc.matches(plain, hash);
6. Implementing Multi-Factor Authentication
| Factor | Type |
|---|---|
| TOTP (Google Authenticator) | Something you have (RFC 6238) |
| WebAuthn / Passkeys | Phishing-resistant |
| SMS code | Weak; SIM swap risk |
| Email code | Backup only |
| Hardware token (FIDO2) | Strongest |
7. Implementing API Key Validation
| Practice | Detail |
|---|---|
| Key prefix | ak_live_... for visibility |
| Hash at rest | SHA-256, never plaintext |
| Show once | On creation only |
| Per-key scopes | Limit blast radius |
| Rotation | Support multiple active keys |
8. Implementing SSO Integration
| Protocol | Use |
|---|---|
| OIDC | Modern web/mobile (built on OAuth 2) |
| SAML 2.0 | Enterprise, legacy |
| CAS | Education sector |
| JIT provisioning | Create user on first login |
9. Handling Token Refresh Logic
Example: Refresh endpoint
@PostMapping("/auth/refresh")
public TokenPair refresh(@RequestBody RefreshRequest req) {
var rt = refreshTokenStore.consume(req.refreshToken()) // single-use
.orElseThrow(() -> new UnauthorizedException("invalid refresh"));
if (rt.expired()) throw new UnauthorizedException("expired");
var newAccess = jwtIssuer.issueAccess(rt.userId());
var newRefresh = refreshTokenStore.issue(rt.userId()); // rotation
return new TokenPair(newAccess, newRefresh);
}
10. Implementing Authentication Filters
| Step | Detail |
|---|---|
| Extract token | From Authorization: Bearer ... |
| Validate | Signature, expiry, issuer |
| Load principal | Map sub claim to user |
| Set context | SecurityContextHolder.setContext(...) |
| On failure | 401 + WWW-Authenticate header |
11. Implementing Remember Me Logic
| Approach | Detail |
|---|---|
| Persistent token | Stored in DB, hash in cookie |
| Cookie attrs | HttpOnly; Secure; SameSite=Lax; Max-Age=30d |
| Rotate on use | Detect token theft |
| Step-up auth | Require fresh login for sensitive ops |
12. Implementing Account Lockout
| Setting | Recommendation |
|---|---|
| Threshold | 5-10 failed attempts |
| Window | 15 minutes |
| Lockout duration | 15-30 min, exponential |
| Per IP + per account | Both |
| CAPTCHA after threshold | Reduce automated attacks |
| Notify user | Email on lockout |