00:00

Stateless vs Stateful Authentication

Last updated:

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

AspectStateful (session)Stateless (credentials or token per request)
Where the login livesServer memory or a shared session storeIn each request
What the client sendsSession ID cookiePassword, API key or signed token
Horizontal scalingNeeds sticky sessions or a shared store such as RedisAny server can handle any request
Logout and revocationImmediate: invalidate the sessionHard: a token stays valid until it expires unless you add a deny list
CSRF exposureYes, cookies are sent automatically; CSRF protection requiredNone for headers the client adds itself; yes if tokens are kept in cookies
Cost per requestA session lookupA password hash check (slow) or a signature check (fast)
Typical clientsServer-rendered web apps in browsersMobile apps, single-page apps calling APIs, service-to-service calls
Spring Security setupformLogin() with default session policyhttpBasic() or oauth2ResourceServer() with STATELESS

3. How Each Approach Handles Requests

Stateful and stateless request handlingStateful: the login creates a session on the server and later requests send only the session cookie. Stateless: every request carries credentials or a token, which the server verifies without stored state. Stateful POST /login password checked once Session store SecurityContext saved Later requests Cookie: JSESSIONID, user loaded from session Stateless Every request credentials or token Verify each time hash or signature check Handled by any server nothing stored, nothing to share
Figure 1: stateful checks the password once and then trusts the session; stateless proves identity on every request.

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());
    }
}

5. Step-by-Step Code Explanation

  1. The API chain matches /api/**, uses HTTP Basic and the STATELESS policy, so no session is ever created for it. CSRF is off because API clients send credentials in a header they add themselves.
  2. The portal chain handles everything else with form login. After a successful login, the SecurityContext is saved in the HTTP session, and the browser receives a new JSESSIONID.
  3. 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:

Terminal
$ 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:

Terminal
$ 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 STATELESS explicitly.
  • 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