Text of docs.spring.io › spring-security › reference › servlet › authentication › session-manag… as Styx crawled it on Nov 18, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Authentication Persistence and Session Management :: Spring Security

Authentication Persistence and Session Management Once you have got an application that is authenticating requests , it is important to consider how that resulting authentication will be persisted and restored on future requests. This is done automatically by default. If you have a custom filter or controller that is setting the security context, you will need to use a SecurityContextRepository to persist it across requests.

If you are upgrading from an older version, you may be interested in the requireExplicitSave setting that preserves Spring Security 5’s default, though note that this is primarily for migration purposes. If you like, you can read more about what requireExplicitSave is doing or why it’s important . Otherwise, in most cases you are done with this section. But before you leave, consider if any of these use cases fit your application: I want to Understand Session Management’s components I want to restrict the number of times a user can be logged in concurrently I want to store the authentication directly myself instead of Spring Security doing it for me I am storing the authentication manually and I want to remove it I am using SessionManagementFilter and I need guidance on moving away from that I want to store the authentication in something other than the session I am using a stateless authentication , but I’d still like to store it in the session I am using SessionCreationPolicy.NEVER but the application is still creating sessions .

Understanding Session Management’s Components The Session Management support is composed of a few components that work together to provide the functionality. Those components are, the SecurityContextHolderFilter , the SecurityContextPersistenceFilter and the SessionManagementFilter . In Spring Security 6, the SecurityContextPersistenceFilter and SessionManagementFilter are not set by default. In addition to that, any application should only have either SecurityContextHolderFilter or SecurityContextPersistenceFilter set, never both.

The SessionManagementFilter The SessionManagementFilter checks the contents of the SecurityContextRepository against the current contents of the SecurityContextHolder to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me [ 1 ] . If the repository contains a security context, the filter does nothing.

If it doesn’t, and the thread-local SecurityContext contains a (non-anonymous) Authentication object, the filter assumes they have been authenticated by a previous filter in the stack. It will then invoke the configured SessionAuthenticationStrategy . If the user is not currently authenticated, the filter will check whether an invalid session ID has been requested (because of a timeout, for example) and will invoke the configured InvalidSessionStrategy , if one is set.

The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation SimpleRedirectInvalidSessionStrategy . The latter is also used when configuring an invalid session URL through the namespace, as described earlier . Moving Away From SessionManagementFilter In Spring Security 5, the default configuration relies on SessionManagementFilter to detect if a user just authenticated and invoke the SessionAuthenticationStrategy .

The problem with this is that it means that in a typical setup, the HttpSession must be read for every request. In Spring Security 6, the default is that authentication mechanisms themselves must invoke the SessionAuthenticationStrategy . This means that there is no need to detect when Authentication is done and thus the HttpSession does not need to be read for every request. Things To Consider When Moving Away From SessionManagementFilter In Spring Security 6, the SessionManagementFilter is not used by default, therefore, some methods from the sessionManagement DSL will not have any effect.

Method Replacement sessionAuthenticationErrorUrl Configure an AuthenticationFailureHandler in your authentication mechanism sessionAuthenticationFailureHandler Configure an AuthenticationFailureHandler in your authentication mechanism sessionAuthenticationStrategy Configure an SessionAuthenticationStrategy in your authentication mechanism as discussed above If you try to use any of these methods, an exception will be thrown.

Customizing Where the Authentication Is Stored By default, Spring Security stores the security context for you in the HTTP session. However, here are several reasons you may want to customize that: You may want to call individual setters on the HttpSessionSecurityContextRepository instance You may want to store the security context in a cache or database to enable horizontal scaling First, you need to create an implementation of SecurityContextRepository or use an existing implementation like HttpSessionSecurityContextRepository , then you can set it in HttpSecurity .

Customizing the SecurityContextRepository Java Kotlin XML @Bean public SecurityFilterChain filterChain(HttpSecurity http) { SecurityContextRepository repo = new MyCustomSecurityContextRepository(); http // ... .securityContext((context) -> context .securityContextRepository(repo) ); return http.build(); } @Bean open fun filterChain(http: HttpSecurity): SecurityFilterChain { val repo = MyCustomSecurityContextRepository() http { // ... securityContext { securityContextRepository = repo } } return http.build() } <http security-context-repository-ref="repo"> <!-- ... --> </http> <bean name="repo" class="com.example.MyCustomSecurityContextRepository" /> The above configuration sets the SecurityContextRepository on the SecurityContextHolderFilter and participating authentication filters, like UsernamePasswordAuthenticationFilter .

To also set it in stateless filters, please see how to customize the SecurityContextRepository for Stateless Authentication . If you are using a custom authentication mechanism, you might want to store the Authentication by yourself . Storing the Authentication manually In some cases, for example, you might be authenticating a user manually instead of relying on Spring Security filters. You can use a custom filters or a Spring MVC controller endpoint to do that.

If you want to save the authentication between requests, in the HttpSession , for example, you have to do so: Java private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository(); (1) @PostMapping("/login") public void login(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) { (2) UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated( loginRequest.getUsername(), loginRequest.getPassword()); (3) Authentication authentication = authenticationManager.authenticate(token); (4) SecurityContext context = securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication); (5) securityContextHolderStrategy.setContext(context); securityContextRepository.saveContext(context, request, response); (6) } class LoginRequest { private String username; private String password; // getters and setters } 1 Add the SecurityContextRepository to the controller 2 Inject the HttpServletRequest and HttpServletResponse to be able to save the SecurityContext 3 Create an unauthenticated UsernamePasswordAuthenticationToken using the provided credentials 4 Call AuthenticationManager#authenticate to authenticate the user 5 Create a SecurityContext and set the Authentication in it 6 Save the SecurityContext in the SecurityContextRepository And that’s it.

If you are not sure what securityContextHolderStrategy is in the above example, you can read more about it in the Using SecurityContextStrategy section . Properly Clearing an Authentication If you are using Spring Security’s Logout Support then it handles a lot of stuff for you including c

The rest of this page is on the live site.