Authentication
Authentication (AuthN) verifies identity — who is calling.
Introduction
Authentication (AuthN) verifies identity — who is calling. Common HLD patterns: session cookies, JWT access tokens, OAuth2/OIDC social login, API keys for partners, and mTLS for service-to-service. Authentication happens at the edge (API Gateway) and may propagate claims to downstream services.
Interviews distinguish AuthN from AuthZ. Design login flows, token lifetimes, refresh rotation, and credential storage (bcrypt/Argon2, never plaintext). Security breaches from weak AuthN invalidate entire architectures.
This lesson maps AuthN components in distributed systems and Spring Security integration.
Understanding the topic
Key concepts
- Session-based: server stores session ID in Redis; cookie to browser.
- Token-based JWT: signed claims, stateless verification, short TTL + refresh token.
- OAuth2 authorization code flow: delegate login to Google/Auth0; receive ID token.
- API keys: long-lived partner access with rotation and scopes.
- mTLS: client certificates for service identity in zero-trust mesh.
- MFA step-up for sensitive operations (wire transfer).
sequenceDiagramUser->>Auth: loginAuth->>Auth: verify credentialsAuth-->>User: JWT access token
Internal architecture
Architecture overview
sequenceDiagramUser->>Auth: loginAuth->>Auth: verify credentialsAuth-->>User: JWT access token
Step-by-step explanation
- User → Login API → Auth Service validates credentials → issues JWT (15m) + refresh (7d HttpOnly cookie).
- API Gateway validates JWT signature via JWKS endpoint from Auth Service.
- Downstream services trust gateway or validate JWT locally with shared public key.
- Refresh endpoint rotates refresh token, detects reuse theft.
- Partner B2B: API key in header, hashed at rest, rate limited per key.
- Service accounts: workload identity (IAM/K8s SA) for east-west calls.
Informative example
Spring Security 6 OAuth2 resource server JWT validation at API:
spring:security:oauth2:resourceserver:jwt:issuer-uri: https://auth.techlearningpro.com/realms/shopjwk-set-uri: https://auth.techlearningpro.com/realms/shop/protocol/openid-connect/certs# Java security filter chain snippet@BeanSecurityFilterChain api(HttpSecurity http) throws Exception {return http.csrf(csrf -> csrf.disable()).sessionManagement(s -> s.sessionCreationPolicy(STATELESS)).authorizeHttpRequests(auth -> auth.requestMatchers("/api/v1/public/**").permitAll().anyRequest().authenticated()).oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults())).build();}
Short access token TTL limits exposure. Store refresh tokens securely HttpOnly Secure SameSite=Strict.
Real-world use
Real-world use cases
- E-commerce customer login with Google OAuth and guest checkout.
- Banking mobile app with biometric + server session.
- Healthcare provider SSO via SAML/OIDC to EHR.
- Fintech partner API with mTLS + API key.
Best practices
- Hash passwords with Argon2id or bcrypt — never MD5/SHA1 alone.
- Rotate signing keys with JWKS kid header support.
- Rate limit login and lockout after failed attempts.
- Propagate sub (userId) and scopes in JWT claims minimally.
- Audit authentication events centrally.
- Separate auth service from business microservices.
Common mistakes
- JWT in localStorage vulnerable to XSS — prefer HttpOnly cookie for refresh.
- Long-lived access tokens without revocation plan.
- Secrets in JWT payload — JWT is signed not encrypted.
- Rolling custom crypto instead of OIDC standards.
- Same auth for admin and consumer without step-up MFA.
Advanced interview questions
Q1BeginnerAuthentication vs authorization?
Q2BeginnerJWT vs session cookie?
Q3IntermediateOAuth2 authorization code flow?
Q4IntermediateHow revoke JWT before expiry?
Q5AdvancedDesign auth for multi-tenant B2B SaaS.
Summary
Authentication verifies caller identity at system edge. JWT + OAuth2/OIDC are standard for modern APIs. Short access tokens, secure refresh rotation, MFA for sensitive ops. API keys and mTLS serve partners and service identities. Never store plaintext passwords; use established IdP where possible. Authorization applies permissions after identity established.