Spring Security Authentication Flow
Understand the servlet filter chain, authentication providers, SecurityContext, session and token trade-offs, authorization, and refresh-token reuse detection.
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
Authenticated API request
Simple example
@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 cookie | Bearer access token |
|---|---|
| Server stores authentication state | Resource server validates token and claims |
| Browser sends cookie automatically | Client explicitly supplies Authorization header |
| Immediate server-side invalidation is straightforward | Revocation needs short expiry, introspection, or server state |
| CSRF protection normally required for unsafe browser requests | Bearer header is not automatically added cross-site, but XSS/token theft remains |
| Good default for one web application | Useful 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
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
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
Authorize
Enforce coarse route permissions, then method-level permission and resource ownership; use database predicates for sensitive ownership where possible.
- 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
| Decision | Benefit | Cost |
|---|---|---|
| Session | Simple revocation and compact cookie | Shared session infrastructure when scaling |
| Self-contained JWT | Independent validation | Revocation and claim staleness |
| BCrypt | Widely supported adaptive hash | Work-factor tuning |
| Argon2 | Memory-hard design | Memory 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
Session
Implement a session login with Secure, HttpOnly, SameSite policy, CSRF protection, fixation defense, and logout tests.
- 2
Token
Implement short-lived access tokens and rotating refresh-token families with hashed storage and reuse detection.
- 3
Authorize
Protect an owner-scoped Task endpoint and an admin endpoint at route, method, and query levels.
- 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.
Servlet Authentication Architecture (opens in a new tab)
Spring · official-docs
Spring Security Java Configuration (opens in a new tab)
Spring · official-docs
Application Security Verification Standard 5.0 (opens in a new tab)
OWASP · standard
RFC 7519 — JSON Web Token (opens in a new tab)
IETF · standard
RFC 8725 — JSON Web Token Best Current Practices (opens in a new tab)
IETF · standard
RFC 9700 — Best Current Practice for OAuth 2.0 Security (opens in a new tab)
IETF · standard