High-Level Design Tutorial 0/42 lessons ~6 min read Lesson 30

    Authentication

    Authentication (AuthN) verifies identity — who is calling.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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).
    text
    sequenceDiagram
    User->>Auth: login
    Auth->>Auth: verify credentials
    Auth-->>User: JWT access token

    Internal architecture

    Architecture overview

    text
    sequenceDiagram
    User->>Auth: login
    Auth->>Auth: verify credentials
    Auth-->>User: JWT access token

    Step-by-step explanation

    1. User → Login API → Auth Service validates credentials → issues JWT (15m) + refresh (7d HttpOnly cookie).
    2. API Gateway validates JWT signature via JWKS endpoint from Auth Service.
    3. Downstream services trust gateway or validate JWT locally with shared public key.
    4. Refresh endpoint rotates refresh token, detects reuse theft.
    5. Partner B2B: API key in header, hashed at rest, rate limited per key.
    6. Service accounts: workload identity (IAM/K8s SA) for east-west calls.

    Informative example

    Spring Security 6 OAuth2 resource server JWT validation at API:

    yaml
    spring:
    security:
    oauth2:
    resourceserver:
    jwt:
    issuer-uri: https://auth.techlearningpro.com/realms/shop
    jwk-set-uri: https://auth.techlearningpro.com/realms/shop/protocol/openid-connect/certs
    # Java security filter chain snippet
    @Bean
    SecurityFilterChain 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?
    AuthN verifies identity (who); AuthZ checks permissions (what they can do).
    Q2BeginnerJWT vs session cookie?
    JWT stateless scalable verification; session server-side easier revoke — often hybrid with short JWT + refresh.
    Q3IntermediateOAuth2 authorization code flow?
    Client redirects user to IdP, receives code, exchanges for tokens server-side — safest for SPAs with PKCE.
    Q4IntermediateHow revoke JWT before expiry?
    Short TTL + refresh denylist in Redis, or session version claim bumped on logout.
    Q5AdvancedDesign auth for multi-tenant B2B SaaS.
    OIDC per tenant optional, API keys hashed, mTLS tier-1, JWT tenant_id claim, gateway validates, SCIM provisioning, audit log, MFA enforced admin.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.