Stateless vs Stateful Authentication
Stateless and stateful authentication differ in one question: after a user proves who they are, does the server remember it? In stateful authentication, the server stores the login in a session and the client sends only a session ID. In stateless authentication, the server stores nothing, and every request carries proof of identity, such as a password or a signed token.
Both are supported by Spring Security, and many systems use both at once. This tutorial compares them on the points that matter in production (scaling, logout, CSRF, cost per request), measures that cost on a running application, and gives clear rules for choosing.
1. What Are Stateful and Stateless Authentication?
Stateful authentication creates server-side state at login. Spring Security saves the SecurityContext in the HTTP session; the browser receives a JSESSIONID cookie and sends it with each request, and SecurityContextHolderFilter loads the user from the session. Form login works this way.
Stateless authentication keeps no login state on the server. Each request is authenticated on its own: with a password (HTTP Basic), an API key, or a signed token such as a JWT that the server can verify without looking anything up. In Spring Security this means SessionCreationPolicy.STATELESS.
2. Stateless vs Stateful: Key Differences
| Aspect | Stateful (session) | Stateless (credentials or token per request) |
|---|---|---|
| Where the login lives | Server memory or a shared session store | In each request |
| What the client sends | Session ID cookie | Password, API key or signed token |
| Horizontal scaling | Needs sticky sessions or a shared store such as Redis | Any server can handle any request |
| Logout and revocation | Immediate: invalidate the session | Hard: a token stays valid until it expires unless you add a deny list |
| CSRF exposure | Yes, cookies are sent automatically; CSRF protection required | None for headers the client adds itself; yes if tokens are kept in cookies |
| Cost per request | A session lookup | A password hash check (slow) or a signature check (fast) |
| Typical clients | Server-rendered web apps in browsers | Mobile apps, single-page apps calling APIs, service-to-service calls |
| Spring Security setup | formLogin() with default session policy | httpBasic() or oauth2ResourceServer() with STATELESS |
3. How Each Approach Handles Requests
The important difference is where the expensive work happens. A password check is deliberately slow (see BCrypt). Stateful login pays that cost once. Stateless Basic authentication pays it on every request. Stateless token authentication avoids it by checking a signature instead, which takes microseconds, but the token cannot easily be withdrawn before it expires.
4. A Complete Example: One App, Both Styles
A ticket booking service offers a browser portal under /portal/** (form login, sessions) and a stateless API under /api/** (HTTP Basic) for partner systems. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2 and Spring Security's generated login page.
package com.javabytechie.tickets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
// Stateless: partner systems send credentials with every call
@Bean
@Order(1)
SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**")
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()); // no cookies are involved
return http.build();
}
// Stateful: browser users log in once and keep a session
@Bean
@Order(2)
SecurityFilterChain portalChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form.defaultSuccessUrl("/portal/tickets"));
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo user only
return new InMemoryUserDetailsManager(
User.withUsername("isha").password(encoder.encode("isha-pass")).roles("AGENT").build());
}
}
package com.javabytechie.tickets;
import java.security.Principal;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TicketController {
@GetMapping({"/api/tickets", "/portal/tickets"})
public List<String> tickets(Principal principal) {
return List.of(principal.getName() + ": Mumbai to Goa, 22 Dec, seat 14C");
}
}
package com.javabytechie.tickets;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TicketApplication {
public static void main(String[] args) {
SpringApplication.run(TicketApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- The API chain matches
/api/**, uses HTTP Basic and theSTATELESSpolicy, so no session is ever created for it. CSRF is off because API clients send credentials in a header they add themselves. - The portal chain handles everything else with form login. After a successful login, the
SecurityContextis saved in the HTTP session, and the browser receives a newJSESSIONID. - The same controller method serves both paths, so any difference in the measurements comes from authentication, not from the business code.
6. Expected Output
Three stateless API calls, each with credentials, and then one call that shows the response headers:
$ for i in 1 2 3; do curl -s -o /dev/null -w '%{http_code} in %{time_total}s\n' -u isha:isha-pass localhost:8080/api/tickets; done
200 in 0.164794s
200 in 0.059787s
200 in 0.070541s
$ curl -u isha:isha-pass localhost:8080/api/tickets
HTTP/1.1 200
["isha: Mumbai to Goa, 22 Dec, seat 14C"]
Once the JVM has warmed up (the first call is always slower), each call takes about 60 milliseconds, because Spring Security verifies the BCrypt hash every time. No Set-Cookie header is sent. Now the stateful portal: one login, then three requests with only the session cookie:
$ CSRF=$(curl -s -c cookies.txt localhost:8080/login | grep -o 'name="_csrf" type="hidden" value="[^"]*"' | cut -d'"' -f6)
$ curl -b cookies.txt -c cookies.txt -X POST localhost:8080/login -d username=isha -d password=isha-pass -d _csrf=$CSRF
HTTP/1.1 302
Location: http://localhost:8080/portal/tickets
$ for i in 1 2 3; do curl -s -o /dev/null -w '%{http_code} in %{time_total}s\n' -b cookies.txt localhost:8080/portal/tickets; done
200 in 0.029932s
200 in 0.001790s
200 in 0.001486s
After the single login and a first warm-up request, each request is answered in about 2 milliseconds, because the server only looks up the session. Exact times depend on the machine (these were measured locally on an Apple M4), but the gap is the point: per-request password checks are expensive. That is why high-traffic stateless APIs use signed tokens rather than passwords.
7. When to Use Each Approach
- Choose stateful for server-rendered web applications used in browsers, admin consoles and any system where immediate logout or session revocation matters.
- Choose stateless for APIs consumed by mobile apps, partner systems and other services, especially when they run on many instances behind a load balancer. Prefer short-lived signed tokens from an identity provider (see OAuth2 resource server) over passwords on every call.
- Combine them when one application serves both audiences, using two chains as shown above. A popular variant for single-page apps is the "backend for frontend" pattern: the browser holds a session cookie with a small server, which calls APIs with tokens.
8. Common Mistakes and Best Practices
- Calling an app stateless because it uses JWT, while storing the token in a cookie. Cookies are sent automatically, so CSRF protection is needed again.
- Long-lived stateless tokens. Without revocation, a stolen token works until it expires. Keep access tokens short-lived.
- Stateful apps on several servers without a shared session store. Users are logged out whenever the load balancer switches servers. Use Spring Session with Redis or JDBC, or sticky sessions.
- Leaving the default session policy on an API chain. Other components may still create sessions. Set
STATELESSexplicitly. - Forgetting the cost of stateless Basic. As measured above, every request repeats the slow password check.
9. Summary
- Stateful authentication stores the login in a server-side session; the client sends only a session cookie.
- Stateless authentication stores nothing; every request carries credentials or a signed token.
- Stateful gives easy logout but needs CSRF protection and shared sessions for scaling.
- Stateless scales easily but makes revocation harder; Basic credentials cost a slow hash check on every call.
- Spring Security supports both, even in one application through separate filter chains.
10. References
Frequently Asked Questions (FAQ)
Q1. Is JWT authentication always stateless?
Only if the server keeps no per-user state and the token is sent in a header. If you store tokens in a server-side deny list or in cookies, parts of the design become stateful or cookie-based again.
Q2. How do I make a Spring Security API stateless?
Use a per-request mechanism such as httpBasic() or oauth2ResourceServer(), and set sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) so no session is created.
Q3. Why do stateful applications need CSRF protection?
Browsers attach session cookies automatically to requests sent to your site, even when another site triggers them. The CSRF token proves that the request came from your own pages.
Q4. Which is faster, stateless or stateful authentication?
It depends on the mechanism. A session lookup is fast. Stateless Basic authentication is slow because it verifies a password hash on every request. Stateless signed tokens are fast because verifying a signature is cheap.
Q5. How do I scale stateful sessions across several servers?
Store sessions in a shared store with Spring Session (for example Redis or JDBC), or configure sticky sessions on the load balancer so each user stays on one server.