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

AspectDetail
StorageServer-side (Redis), HTTP-only cookie holds ID
Cookie flagsHttpOnly; Secure; SameSite=Lax
Idle timeout30 min default
Absolute timeout8-12h max
Rotate on auth eventsPrevent fixation

4. Implementing OAuth 2.0 Client

FlowUse
Authorization Code + PKCEWeb/mobile/SPA (recommended)
Client CredentialsService-to-service
Device CodeInput-constrained devices
ImplicitDEPRECATED
Resource Owner PasswordDEPRECATED

5. Designing Password Storage

AlgorithmRecommendation
Argon2idPreferred for new systems
bcryptAcceptable; use cost ≥ 12
scryptAcceptable; memory-hard
PBKDF2Use ≥ 600k iterations (SHA-256)
MD5/SHA-1/plainNEVER

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

FactorType
TOTP (Google Authenticator)Something you have (RFC 6238)
WebAuthn / PasskeysPhishing-resistant
SMS codeWeak; SIM swap risk
Email codeBackup only
Hardware token (FIDO2)Strongest

7. Implementing API Key Validation

PracticeDetail
Key prefixak_live_... for visibility
Hash at restSHA-256, never plaintext
Show onceOn creation only
Per-key scopesLimit blast radius
RotationSupport multiple active keys

8. Implementing SSO Integration

ProtocolUse
OIDCModern web/mobile (built on OAuth 2)
SAML 2.0Enterprise, legacy
CASEducation sector
JIT provisioningCreate 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

StepDetail
Extract tokenFrom Authorization: Bearer ...
ValidateSignature, expiry, issuer
Load principalMap sub claim to user
Set contextSecurityContextHolder.setContext(...)
On failure401 + WWW-Authenticate header

11. Implementing Remember Me Logic

ApproachDetail
Persistent tokenStored in DB, hash in cookie
Cookie attrsHttpOnly; Secure; SameSite=Lax; Max-Age=30d
Rotate on useDetect token theft
Step-up authRequire fresh login for sensitive ops

12. Implementing Account Lockout

SettingRecommendation
Threshold5-10 failed attempts
Window15 minutes
Lockout duration15-30 min, exponential
Per IP + per accountBoth
CAPTCHA after thresholdReduce automated attacks
Notify userEmail on lockout