exit lab
Backend Engineering
Level 6·security·system·intermediate

Spring Security Authentication Flow

Understand the servlet filter chain, authentication providers, SecurityContext, session and token trade-offs, authorization, and refresh-token reuse detection.

65 minutes Spring Security 6.5 servlet applications; forward-compatible concepts for Security 7 Updated 2026-07-16
Spring Security 6.5Java 21JWTHTTP Cookies

Learning objectives

  • Trace credential processing through Spring Security components
  • Choose session or token authentication from deployment and threat constraints

What it is

Spring Security is a servlet-filter-based security framework. Authentication turns presented credentials into a trusted Authentication; authorization decides whether that principal may perform a specific action. Sessions and bearer tokens are alternative ways to carry authenticated context, not security rankings.

Why it matters

Security bugs often come from incorrect flow assumptions: a JWT is parsed but not fully validated, CSRF is disabled because an API returns JSON, roles are checked without resource ownership, or logout clears a browser value while a reusable refresh token remains active.

How it works

Username/password authentication

Login request
Security filter
AuthenticationManager
AuthenticationProvider
UserDetailsService
PasswordEncoder
Authenticated principal
SecurityContext
Session or tokens
Text alternative: A login request reaches a security filter, which sends an authentication token to AuthenticationManager and a compatible AuthenticationProvider. UserDetailsService loads identity data and PasswordEncoder verifies the password. On success the authenticated principal enters the SecurityContext and is persisted by a session or represented with tokens.

Authenticated API request

Request credential
SecurityFilterChain
Validate session or bearer token
SecurityContext
Endpoint authorization
Method/ownership check
Controller
Text alternative: Each protected request passes through SecurityFilterChain, which validates the session cookie or bearer token, populates SecurityContext, enforces endpoint rules, and then allows method and resource-ownership checks before controller work.

Simple example

SecurityConfig.java
@Configuration
@EnableMethodSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers(HttpMethod.POST, "/v1/auth/login").permitAll()
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers("/v1/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .sessionManagement(session -> session
                .sessionFixation(fixation -> fixation.changeSessionId()))
            .build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

Backend example

Session cookieBearer access token
Server stores authentication stateResource server validates token and claims
Browser sends cookie automaticallyClient explicitly supplies Authorization header
Immediate server-side invalidation is straightforwardRevocation needs short expiry, introspection, or server state
CSRF protection normally required for unsafe browser requestsBearer header is not automatically added cross-site, but XSS/token theft remains
Good default for one web applicationUseful across independent clients/services and delegated authorization

A JWT is a signed claim container. Verify allowed algorithms, signature, issuer, audience, expiration/not-before, and application authorization claims. Do not place secrets in the payload; base64url encoding is not encryption.

Production example

  1. 1

    Login

    Rate-limit by multiple signals, load the account, verify an adaptive password hash, rotate the session identifier or create short-lived access and high-entropy refresh credentials, and emit an audit event.

  2. 2

    Refresh

    Store a hash or identifier for each refresh token family. Rotate on every successful use. If an invalidated token is reused, revoke the active family and require fresh authentication.

  3. 3

    Authorize

    Enforce coarse route permissions, then method-level permission and resource ownership; use database predicates for sensitive ownership where possible.

  4. 4

    Logout/reset

    Invalidate the server session or refresh-token family, clear the client credential safely, and decide whether password change revokes other active sessions.

Common mistakes

  • Presenting JWT as automatically better than sessions
  • Building a custom password hash
  • Storing long-lived bearer tokens in browser-readable persistent storage without threat analysis
  • Accepting whatever JWT algorithm the header requests
  • Returning the same behavior for authentication and authorization failures without deliberate disclosure policy
  • Relying only on URL roles and skipping ownership

Best practices

  • Use SecurityFilterChain and supported framework components
  • Use adaptive PasswordEncoder algorithms and upgrade hashes over time
  • Keep access tokens short-lived and protect refresh tokens as credentials
  • Validate issuer, audience, time, signature, and allowed algorithms
  • Apply least privilege and deny by default
  • Test 401, 403, ownership, CSRF, session fixation, token reuse, and logout

Trade-offs

DecisionBenefitCost
SessionSimple revocation and compact cookieShared session infrastructure when scaling
Self-contained JWTIndependent validationRevocation and claim staleness
BCryptWidely supported adaptive hashWork-factor tuning
Argon2Memory-hard designMemory tuning and library/operations support

Interview questions

  • Walk through Spring Security authentication components
  • What is stored in SecurityContext?
  • When is CSRF relevant to an API?
  • How do 401 and 403 differ?
  • How does refresh-token rotation detect reuse?
  • Which JWT claims and algorithms must a resource server validate?
  • How do you enforce resource ownership?

Hands-on task

  1. 1

    Session

    Implement a session login with Secure, HttpOnly, SameSite policy, CSRF protection, fixation defense, and logout tests.

  2. 2

    Token

    Implement short-lived access tokens and rotating refresh-token families with hashed storage and reuse detection.

  3. 3

    Authorize

    Protect an owner-scoped Task endpoint and an admin endpoint at route, method, and query levels.

  4. 4

    Attack

    Test brute force, missing/expired/wrong-audience token, CSRF, horizontal access, logout, and refresh reuse.

References

  • Spring: Servlet Authentication Architecture — https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/architecture.html
  • Spring: Spring Security Java Configuration — https://docs.spring.io/spring-security/reference/6.5/servlet/configuration/java.html
  • OWASP: Application Security Verification Standard 5.0 — https://owasp.org/www-project-application-security-verification-standard/
  • IETF: RFC 7519 — JSON Web Token — https://www.rfc-editor.org/rfc/rfc7519
  • IETF: RFC 8725 — JSON Web Token Best Current Practices — https://www.rfc-editor.org/rfc/rfc8725
  • IETF: RFC 9700 — Best Current Practice for OAuth 2.0 Security — https://www.rfc-editor.org/rfc/rfc9700

Retrieval check

Before you continue

  • Explain the main idea in your own words without rereading the page.
  • Name one production problem this knowledge helps prevent.
  • Describe where you would apply it in a Spring Boot project.

Source metadata

Primary references checked on 2026-07-16. Version scope is stated at the top of this page.