2
0

session-management.adoc 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. [[session-mgmt]]
  2. = Authentication Persistence and Session Management
  3. Once you have got an application that is xref:servlet/authentication/index.adoc[authenticating requests], it is important to consider how that resulting authentication will be persisted and restored on future requests.
  4. This is done automatically by default, so no additional code is necessary, though it is important to know what `requireExplicitSave` means in `HttpSecurity`.
  5. If you like, <<how-it-works-requireexplicitsave,you can read more about what requireExplicitSave is doing>> or <<requireexplicitsave,why it's important>>. Otherwise, in most cases you are done with this section.
  6. But before you leave, consider if any of these use cases fit your application:
  7. * I want to <<understanding-session-management-components,Understand Session Management's components>>
  8. * I want to <<ns-concurrent-sessions,restrict the number of times>> a user can be logged in concurrently
  9. * I want <<store-authentication-manually,to store the authentication directly>> myself instead of Spring Security doing it for me
  10. * I am storing the authentication manually and I want <<properly-clearing-authentication,to remove it>>
  11. * I am using <<the-sessionmanagementfilter, `SessionManagementFilter`>> and I need <<moving-away-from-sessionmanagementfilter,guidance on moving away from that>>
  12. * I want to store the authentication <<customizing-where-authentication-is-stored,in something other than the session>>
  13. * I am using a <<stateless-authentication, stateless authentication>>, but <<storing-stateless-authentication-in-the-session,I'd still like to store it in the session>>
  14. * I am using `SessionCreationPolicy.NEVER` but <<never-policy-session-still-created,the application is still creating sessions>>.
  15. [[understanding-session-management-components]]
  16. == Understanding Session Management's Components
  17. The Session Management support is composed of a few components that work together to provide the functionality.
  18. Those components are, xref:servlet/authentication/persistence.adoc#securitycontextholderfilter[the `SecurityContextHolderFilter`], xref:servlet/authentication/persistence.adoc#securitycontextpersistencefilter[the `SecurityContextPersistenceFilter`] and <<the-sessionmanagementfilter,the `SessionManagementFilter`>>.
  19. [NOTE]
  20. =====
  21. In Spring Security 6, the `SecurityContextPersistenceFilter` and `SessionManagementFilter` are not set by default.
  22. In addition to that, any application should only have either `SecurityContextHolderFilter` or `SecurityContextPersistenceFilter` set, never both.
  23. =====
  24. [[the-sessionmanagementfilter]]
  25. === The `SessionManagementFilter`
  26. 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 footnote:[
  27. Authentication by mechanisms which perform a redirect after authenticating (such as form-login) will not be detected by `SessionManagementFilter`, as the filter will not be invoked during the authenticating request.
  28. Session-management functionality has to be handled separately in these cases.
  29. ].
  30. If the repository contains a security context, the filter does nothing.
  31. 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.
  32. It will then invoke the configured `SessionAuthenticationStrategy`.
  33. 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.
  34. The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation `SimpleRedirectInvalidSessionStrategy`.
  35. The latter is also used when configuring an invalid session URL through the namespace, <<session-mgmt,as described earlier>>.
  36. [[moving-away-from-sessionmanagementfilter]]
  37. ==== Moving Away From `SessionManagementFilter`
  38. In Spring Security 5, the default configuration relies on `SessionManagementFilter` to detect if a user just authenticated and invoke {security-api-url}org/springframework/security/web/authentication/session/SessionAuthenticationStrategy.html[the `SessionAuthenticationStrategy`].
  39. The problem with this is that it means that in a typical setup, the `HttpSession` must be read for every request.
  40. In Spring Security 6, the default is that authentication mechanisms themselves must invoke the `SessionAuthenticationStrategy`.
  41. 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.
  42. ==== Things To Consider When Moving Away From `SessionManagementFilter`
  43. In Spring Security 6, the `SessionManagementFilter` is not used by default, therefore, some methods from the `sessionManagement` DSL will not have any effect.
  44. |===
  45. |Method |Replacement
  46. |`sessionAuthenticationErrorUrl`
  47. |Configure an {security-api-url}/org/springframework/security/web/authentication/AuthenticationFailureHandler.html[`AuthenticationFailureHandler`] in your authentication mechanism
  48. |`sessionAuthenticationFailureHandler`
  49. |Configure an {security-api-url}/org/springframework/security/web/authentication/AuthenticationFailureHandler.html[`AuthenticationFailureHandler`] in your authentication mechanism
  50. |`sessionAuthenticationStrategy`
  51. |Configure an `SessionAuthenticationStrategy` in your authentication mechanism as <<moving-away-from-sessionmanagementfilter,discussed above>>
  52. |===
  53. If you try to use any of these methods, an exception will be thrown.
  54. [[customizing-where-authentication-is-stored]]
  55. == Customizing Where the Authentication Is Stored
  56. 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:
  57. * You may want call individual setters on the `HttpSessionSecurityContextRepository` instance
  58. * You may want to store the security context in a cache or database to enable horizontal scaling
  59. First, you need to create an implementation of `SecurityContextRepository` or use an existing implementation like `HttpSessionSecurityContextRepository`, then you can set it in `HttpSecurity`.
  60. [[customizing-the-securitycontextrepository]]
  61. .Customizing the `SecurityContextRepository`
  62. ====
  63. .Java
  64. [source,java,role="primary"]
  65. ----
  66. @Bean
  67. public SecurityFilterChain filterChain(HttpSecurity http) {
  68. SecurityContextRepository repo = new MyCustomSecurityContextRepository();
  69. http
  70. // ...
  71. .securityContext((context) -> context
  72. .securityContextRepository(repo)
  73. );
  74. return http.build();
  75. }
  76. ----
  77. .Kotlin
  78. [source,kotlin,role="secondary"]
  79. ----
  80. @Bean
  81. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  82. val repo = MyCustomSecurityContextRepository()
  83. http {
  84. // ...
  85. securityContext {
  86. securityContextRepository = repo
  87. }
  88. }
  89. return http.build()
  90. }
  91. ----
  92. .XML
  93. [source,xml,role="secondary"]
  94. ----
  95. <http security-context-repository-ref="repo">
  96. <!-- ... -->
  97. </http>
  98. <bean name="repo" class="com.example.MyCustomSecurityContextRepository" />
  99. ----
  100. ====
  101. [NOTE]
  102. ====
  103. The above configuration sets the `SecurityContextRepository` on the `SecurityContextHolderFilter` and **participating** authentication filters, like `UsernamePasswordAuthenticationFilter`.
  104. To also set it in stateless filters, please see <<storing-stateless-authentication-in-the-session,how to customize the `SecurityContextRepository` for Stateless Authentication>>.
  105. ====
  106. If you are using a custom authentication mechanism, you might want to <<store-authentication-manually,store the `Authentication` by yourself>>.
  107. [[store-authentication-manually]]
  108. === Storing the `Authentication` manually
  109. In some cases, for example, you might be authenticating a user manually instead of relying on Spring Security filters.
  110. You can use a custom filters or a {spring-framework-reference-url}/web.html#mvc-controller[Spring MVC controller] endpoint to do that.
  111. If you want to save the authentication between requests, in the `HttpSession`, for example, you have to do so:
  112. ====
  113. .Java
  114. [source,java,role="primary"]
  115. ----
  116. private SecurityContextRepository securityContextRepository =
  117. new HttpSessionSecurityContextRepository(); <1>
  118. @PostMapping("/login")
  119. public void login(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) { <2>
  120. UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(
  121. loginRequest.getUsername(), loginRequest.getPassword()); <3>
  122. Authentication authentication = authenticationManager.authenticate(token); <4>
  123. SecurityContext context = securityContextHolderStrategy.createEmptyContext();
  124. context.setAuthentication(authentication); <5>
  125. securityContextHolderStrategy.setContext(context);
  126. securityContextRepository.saveContext(context, request, response); <6>
  127. }
  128. class LoginRequest {
  129. private String username;
  130. private String password;
  131. // getters and setters
  132. }
  133. ----
  134. ====
  135. <1> Add the `SecurityContextRepository` to the controller
  136. <2> Inject the `HttpServletRequest` and `HttpServletResponse` to be able to save the `SecurityContext`
  137. <3> Create an unauthenticated `UsernamePasswordAuthenticationToken` using the provided credentials
  138. <4> Call `AuthenticationManager#authenticate` to authenticate the user
  139. <5> Create a `SecurityContext` and set the `Authentication` in it
  140. <6> Save the `SecurityContext` in the `SecurityContextRepository`
  141. And that's it.
  142. If you are not sure what `securityContextHolderStrategy` is in the above example, you can read more about it in the <<use-securitycontextholderstrategy, Using `SecurityContextStrategy` section>>.
  143. [[properly-clearing-authentication]]
  144. === Properly Clearing an Authentication
  145. If you are using Spring Security's xref:servlet/authentication/logout.adoc[Logout Support] then it handles a lot of stuff for you including clearing and saving the context.
  146. But, let's say you need to manually log users out of your app. In that case, you'll need to make sure you're xref:servlet/authentication/logout.adoc#creating-custom-logout-endpoint[clearing and saving the context properly].
  147. [[stateless-authentication]]
  148. === Configuring Persistence for Stateless Authentication
  149. Sometimes there is no need to create and maintain a `HttpSession` for example, to persist the authentication across requests.
  150. Some authentication mechanisms like xref:servlet/authentication/passwords/basic.adoc[HTTP Basic] are stateless and, therefore, re-authenticates the user on every request.
  151. If you do not wish to create sessions, you can use `SessionCreationPolicy.STATELESS`, like so:
  152. ====
  153. .Java
  154. [source,java,role="primary"]
  155. ----
  156. @Bean
  157. public SecurityFilterChain filterChain(HttpSecurity http) {
  158. http
  159. // ...
  160. .sessionManagement((session) -> session
  161. .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  162. );
  163. return http.build();
  164. }
  165. ----
  166. .Kotlin
  167. [source,kotlin,role="secondary"]
  168. ----
  169. @Bean
  170. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  171. http {
  172. // ...
  173. sessionManagement {
  174. sessionCreationPolicy = SessionCreationPolicy.STATELESS
  175. }
  176. }
  177. return http.build()
  178. }
  179. ----
  180. .XML
  181. [source,xml,role="secondary"]
  182. ----
  183. <http create-session="stateless">
  184. <!-- ... -->
  185. </http>
  186. ----
  187. ====
  188. The above configuration is <<customizing-where-authentication-is-stored, configuring the `SecurityContextRepository`>> to use a `NullSecurityContextRepository` and is also xref:servlet/architecture.adoc#requestcache-prevent-saved-request[preventing the request from being saved in the session].
  189. [[never-policy-session-still-created]]
  190. If you are using `SessionCreationPolicy.NEVER`, you might notice that the application is still creating a `HttpSession`.
  191. In most cases, this happens because the xref:servlet/architecture.adoc#savedrequests[request is saved in the session] for the authenticated resource to re-request after authentication is successful.
  192. To avoid that, please refer to xref:servlet/architecture.adoc#requestcache-prevent-saved-request[how to prevent the request of being saved] section.
  193. [[storing-stateless-authentication-in-the-session]]
  194. ==== Storing Stateless Authentication in the Session
  195. If, for some reason, you are using a stateless authentication mechanism, but you still want to store the authentication in the session you can use the `HttpSessionSecurityContextRepository` instead of the `NullSecurityContextRepository`.
  196. For the xref:servlet/authentication/passwords/basic.adoc[HTTP Basic], you can add xref:servlet/configuration/java.adoc#post-processing-configured-objects[a `ObjectPostProcessor`] that changes the `SecurityContextRepository` used by the `BasicAuthenticationFilter`:
  197. .Store HTTP Basic authentication in the `HttpSession`
  198. ====
  199. .Java
  200. [source,java,role="primary"]
  201. ----
  202. @Bean
  203. SecurityFilterChain web(HttpSecurity http) throws Exception {
  204. http
  205. // ...
  206. .httpBasic((basic) -> basic
  207. .addObjectPostProcessor(new ObjectPostProcessor<BasicAuthenticationFilter>() {
  208. @Override
  209. public <O extends BasicAuthenticationFilter> O postProcess(O filter) {
  210. filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
  211. return filter;
  212. }
  213. })
  214. );
  215. return http.build();
  216. }
  217. ----
  218. ====
  219. The above also applies to others authentication mechanisms, like xref:servlet/oauth2/resource-server/index.adoc[Bearer Token Authentication].
  220. [[requireexplicitsave]]
  221. == Understanding Require Explicit Save
  222. In Spring Security 5, the default behavior is for the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontext[`SecurityContext`] to automatically be saved to the xref:servlet/authentication/persistence.adoc#securitycontextrepository[`SecurityContextRepository`] using the <<securitycontextpersistencefilter, `SecurityContextPersistenceFilter`>>.
  223. Saving must be done just prior to the `HttpServletResponse` being committed and just before `SecurityContextPersistenceFilter`.
  224. Unfortunately, automatic persistence of the `SecurityContext` can surprise users when it is done prior to the request completing (i.e. just prior to committing the `HttpServletResponse`).
  225. It also is complex to keep track of the state to determine if a save is necessary causing unnecessary writes to the `SecurityContextRepository` (i.e. `HttpSession`) at times.
  226. For these reasons, the `SecurityContextPersistenceFilter` has been deprecated to be replaced with the `SecurityContextHolderFilter`.
  227. In Spring Security 6, the default behavior is that xref:servlet/authentication/persistence.adoc#securitycontextholderfilter[the `SecurityContextHolderFilter`] will only read the `SecurityContext` from `SecurityContextRepository` and populate it in the `SecurityContextHolder`.
  228. Users now must explicitly save the `SecurityContext` with the `SecurityContextRepository` if they want the `SecurityContext` to persist between requests.
  229. This removes ambiguity and improves performance by only requiring writing to the `SecurityContextRepository` (i.e. `HttpSession`) when it is necessary.
  230. [[how-it-works-requireexplicitsave]]
  231. === How it works
  232. In summary, when `requireExplicitSave` is `true`, Spring Security sets up xref:servlet/authentication/persistence.adoc#securitycontextholderfilter[the `SecurityContextHolderFilter`] instead of xref:servlet/authentication/persistence.adoc#securitycontextpersistencefilter[the `SecurityContextPersistenceFilter`]
  233. [[ns-concurrent-sessions]]
  234. == Configuring Concurrent Session Control
  235. If you wish to place constraints on a single user's ability to log in to your application, Spring Security supports this out of the box with the following simple additions.
  236. First, you need to add the following listener to your configuration to keep Spring Security updated about session lifecycle events:
  237. ====
  238. .Java
  239. [source,java,role="primary"]
  240. ----
  241. @Bean
  242. public HttpSessionEventPublisher httpSessionEventPublisher() {
  243. return new HttpSessionEventPublisher();
  244. }
  245. ----
  246. .Kotlin
  247. [source,kotlin,role="secondary"]
  248. ----
  249. @Bean
  250. open fun httpSessionEventPublisher(): HttpSessionEventPublisher {
  251. return HttpSessionEventPublisher()
  252. }
  253. ----
  254. .web.xml
  255. [source,xml,role="secondary"]
  256. ----
  257. <listener>
  258. <listener-class>
  259. org.springframework.security.web.session.HttpSessionEventPublisher
  260. </listener-class>
  261. </listener>
  262. ----
  263. ====
  264. Then add the following lines to your security configuration:
  265. ====
  266. .Java
  267. [source,java,role="primary"]
  268. ----
  269. @Bean
  270. public SecurityFilterChain filterChain(HttpSecurity http) {
  271. http
  272. .sessionManagement(session -> session
  273. .maximumSessions(1)
  274. );
  275. return http.build();
  276. }
  277. ----
  278. .Kotlin
  279. [source,kotlin,role="secondary"]
  280. ----
  281. @Bean
  282. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  283. http {
  284. sessionManagement {
  285. sessionConcurrency {
  286. maximumSessions = 1
  287. }
  288. }
  289. }
  290. return http.build()
  291. }
  292. ----
  293. .XML
  294. [source,xml,role="secondary"]
  295. ----
  296. <http>
  297. ...
  298. <session-management>
  299. <concurrency-control max-sessions="1" />
  300. </session-management>
  301. </http>
  302. ----
  303. ====
  304. This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated.
  305. Using Spring Boot, you can test the above configuration scenario the following way:
  306. ====
  307. .Java
  308. [source,java,role="primary"]
  309. ----
  310. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  311. @AutoConfigureMockMvc
  312. public class MaximumSessionsTests {
  313. @Autowired
  314. private MockMvc mvc;
  315. @Test
  316. void loginOnSecondLoginThenFirstSessionTerminated() throws Exception {
  317. MvcResult mvcResult = this.mvc.perform(formLogin())
  318. .andExpect(authenticated())
  319. .andReturn();
  320. MockHttpSession firstLoginSession = (MockHttpSession) mvcResult.getRequest().getSession();
  321. this.mvc.perform(get("/").session(firstLoginSession))
  322. .andExpect(authenticated());
  323. this.mvc.perform(formLogin()).andExpect(authenticated());
  324. // first session is terminated by second login
  325. this.mvc.perform(get("/").session(firstLoginSession))
  326. .andExpect(unauthenticated());
  327. }
  328. }
  329. ----
  330. ====
  331. You can try it using the {gh-samples-url}/servlet/spring-boot/java/session-management/maximum-sessions[Maximum Sessions sample].
  332. It is also common that you would prefer to prevent a second login, in which case you can use:
  333. ====
  334. .Java
  335. [source,java,role="primary"]
  336. ----
  337. @Bean
  338. public SecurityFilterChain filterChain(HttpSecurity http) {
  339. http
  340. .sessionManagement(session -> session
  341. .maximumSessions(1)
  342. .maxSessionsPreventsLogin(true)
  343. );
  344. return http.build();
  345. }
  346. ----
  347. .Kotlin
  348. [source,kotlin,role="secondary"]
  349. ----
  350. @Bean
  351. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  352. http {
  353. sessionManagement {
  354. sessionConcurrency {
  355. maximumSessions = 1
  356. maxSessionsPreventsLogin = true
  357. }
  358. }
  359. }
  360. return http.build()
  361. }
  362. ----
  363. .XML
  364. [source,xml,role="secondary"]
  365. ----
  366. <http>
  367. <session-management>
  368. <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
  369. </session-management>
  370. </http>
  371. ----
  372. ====
  373. The second login will then be rejected.
  374. By "rejected", we mean that the user will be sent to the `authentication-failure-url` if form-based login is being used.
  375. If the second authentication takes place through another non-interactive mechanism, such as "remember-me", an "unauthorized" (401) error will be sent to the client.
  376. If instead you want to use an error page, you can add the attribute `session-authentication-error-url` to the `session-management` element.
  377. Using Spring Boot, you can test the above configuration the following way:
  378. ====
  379. .Java
  380. [source,java,role="primary"]
  381. ----
  382. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  383. @AutoConfigureMockMvc
  384. public class MaximumSessionsPreventLoginTests {
  385. @Autowired
  386. private MockMvc mvc;
  387. @Test
  388. void loginOnSecondLoginThenPreventLogin() throws Exception {
  389. MvcResult mvcResult = this.mvc.perform(formLogin())
  390. .andExpect(authenticated())
  391. .andReturn();
  392. MockHttpSession firstLoginSession = (MockHttpSession) mvcResult.getRequest().getSession();
  393. this.mvc.perform(get("/").session(firstLoginSession))
  394. .andExpect(authenticated());
  395. // second login is prevented
  396. this.mvc.perform(formLogin()).andExpect(unauthenticated());
  397. // first session is still valid
  398. this.mvc.perform(get("/").session(firstLoginSession))
  399. .andExpect(authenticated());
  400. }
  401. }
  402. ----
  403. ====
  404. If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly.
  405. You can try it using the {gh-samples-url}/servlet/spring-boot/java/session-management/maximum-sessions-prevent-login[Maximum Sessions Prevent Login sample].
  406. == Detecting Timeouts
  407. Sessions expire on their own, and there is nothing that needs to be done to ensure that a security context gets removed.
  408. That said, Spring Security can detect when a session has expired and take specific actions that you indicate.
  409. For example, you may want to redirect to a specific endpoint when a user makes a request with an already-expired session.
  410. This is achieved through the `invalidSessionUrl` in `HttpSecurity`:
  411. ====
  412. .Java
  413. [source,java,role="primary"]
  414. ----
  415. @Bean
  416. public SecurityFilterChain filterChain(HttpSecurity http) {
  417. http
  418. .sessionManagement(session -> session
  419. .invalidSessionUrl("/invalidSession")
  420. );
  421. return http.build();
  422. }
  423. ----
  424. .Kotlin
  425. [source,kotlin,role="secondary"]
  426. ----
  427. @Bean
  428. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  429. http {
  430. sessionManagement {
  431. invalidSessionUrl = "/invalidSession"
  432. }
  433. }
  434. return http.build()
  435. }
  436. ----
  437. .XML
  438. [source,xml,role="secondary"]
  439. ----
  440. <http>
  441. ...
  442. <session-management invalid-session-url="/invalidSession" />
  443. </http>
  444. ----
  445. ====
  446. Note that if you use this mechanism to detect session timeouts, it may falsely report an error if the user logs out and then logs back in without closing the browser.
  447. This is because the session cookie is not cleared when you invalidate the session and will be resubmitted even if the user has logged out.
  448. If that is your case, you might want to <<clearing-session-cookie-on-logout,configure logout to clear the session cookie>>.
  449. === Customizing the Invalid Session Strategy
  450. The `invalidSessionUrl` is a convenience method for setting the `InvalidSessionStrategy` using the {security-api-url}/org/springframework/security/web/session/SimpleRedirectInvalidSessionStrategy.html[`SimpleRedirectInvalidSessionStrategy` implementation].
  451. If you want to customize the behavior, you can implement the {security-api-url}/org/springframework/security/web/session/InvalidSessionStrategy.html[`InvalidSessionStrategy`] interface and configure it using the `invalidSessionStrategy` method:
  452. ====
  453. .Java
  454. [source,java,role="primary"]
  455. ----
  456. @Bean
  457. public SecurityFilterChain filterChain(HttpSecurity http) {
  458. http
  459. .sessionManagement(session -> session
  460. .invalidSessionStrategy(new MyCustomInvalidSessionStrategy())
  461. );
  462. return http.build();
  463. }
  464. ----
  465. .Kotlin
  466. [source,kotlin,role="secondary"]
  467. ----
  468. @Bean
  469. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  470. http {
  471. sessionManagement {
  472. invalidSessionStrategy = MyCustomInvalidSessionStrategy()
  473. }
  474. }
  475. return http.build()
  476. }
  477. ----
  478. .XML
  479. [source,xml,role="secondary"]
  480. ----
  481. <http>
  482. ...
  483. <session-management invalid-session-strategy-ref="myCustomInvalidSessionStrategy" />
  484. <bean name="myCustomInvalidSessionStrategy" class="com.example.MyCustomInvalidSessionStrategy" />
  485. </http>
  486. ----
  487. ====
  488. [[clearing-session-cookie-on-logout]]
  489. == Clearing Session Cookies on Logout
  490. You can explicitly delete the JSESSIONID cookie on logging out, for example by using the https://w3c.github.io/webappsec-clear-site-data/[`Clear-Site-Data` header] in the logout handler:
  491. ====
  492. .Java
  493. [source,java,role="primary"]
  494. ----
  495. @Bean
  496. public SecurityFilterChain filterChain(HttpSecurity http) {
  497. http
  498. .logout((logout) -> logout
  499. .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(COOKIES)))
  500. );
  501. return http.build();
  502. }
  503. ----
  504. .Kotlin
  505. [source,kotlin,role="secondary"]
  506. ----
  507. @Bean
  508. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  509. http {
  510. logout {
  511. addLogoutHandler(HeaderWriterLogoutHandler(ClearSiteDataHeaderWriter(COOKIES)))
  512. }
  513. }
  514. return http.build()
  515. }
  516. ----
  517. .XML
  518. [source,xml,role="secondary"]
  519. ----
  520. <http>
  521. <logout success-handler-ref="clearSiteDataHandler" />
  522. <b:bean id="clearSiteDataHandler" class="org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler">
  523. <b:constructor-arg>
  524. <b:bean class="org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter">
  525. <b:constructor-arg>
  526. <b:list>
  527. <b:value>COOKIES</b:value>
  528. </b:list>
  529. </b:constructor-arg>
  530. </b:bean>
  531. </b:constructor-arg>
  532. </b:bean>
  533. </http>
  534. ----
  535. ====
  536. This has the advantage of being container agnostic and will work with any container that supports the `Clear-Site-Data` header.
  537. As an alternative, you can also use the following syntax in the logout handler:
  538. ====
  539. .Java
  540. [source,java,role="primary"]
  541. ----
  542. @Bean
  543. public SecurityFilterChain filterChain(HttpSecurity http) {
  544. http
  545. .logout(logout -> logout
  546. .deleteCookies("JSESSIONID")
  547. );
  548. return http.build();
  549. }
  550. ----
  551. .Kotlin
  552. [source,kotlin,role="secondary"]
  553. ----
  554. @Bean
  555. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  556. http {
  557. logout {
  558. deleteCookies("JSESSIONID")
  559. }
  560. }
  561. return http.build()
  562. }
  563. ----
  564. .XML
  565. [source,xml,role="secondary"]
  566. ----
  567. <http>
  568. <logout delete-cookies="JSESSIONID" />
  569. </http>
  570. ----
  571. ====
  572. Unfortunately, this cannot be guaranteed to work with every servlet container, so you need to test it in your environment.
  573. [NOTE]
  574. =====
  575. If you run your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server.
  576. For example, by using Apache HTTPD's `mod_headers`, the following directive deletes the `JSESSIONID` cookie by expiring it in the response to a logout request (assuming the application is deployed under the `/tutorial` path):
  577. =====
  578. ====
  579. [source,xml]
  580. ----
  581. <LocationMatch "/tutorial/logout">
  582. Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT"
  583. </LocationMatch>
  584. ----
  585. ====
  586. More details on the xref:servlet/exploits/headers.adoc#servlet-headers-clear-site-data[Clear Site Data] and xref:servlet/authentication/logout.adoc[Logout sections].
  587. [[ns-session-fixation]]
  588. == Understanding Session Fixation Attack Protection
  589. https://en.wikipedia.org/wiki/Session_fixation[Session fixation] attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example).
  590. Spring Security protects against this automatically by creating a new session or otherwise changing the session ID when a user logs in.
  591. === Configuring Session Fixation Protection
  592. You can control the strategy for Session Fixation Protection by choosing between three recommended options:
  593. * `changeSessionId` - Do not create a new session.
  594. Instead, use the session fixation protection provided by the Servlet container (`HttpServletRequest#changeSessionId()`).
  595. This option is only available in Servlet 3.1 (Java EE 7) and newer containers.
  596. Specifying it in older containers will result in an exception.
  597. This is the default in Servlet 3.1 and newer containers.
  598. * `newSession` - Create a new "clean" session, without copying the existing session data (Spring Security-related attributes will still be copied).
  599. * `migrateSession` - Create a new session and copy all existing session attributes to the new session.
  600. This is the default in Servlet 3.0 or older containers.
  601. You can configure the session fixation protection by doing:
  602. ====
  603. .Java
  604. [source,java,role="primary"]
  605. ----
  606. @Bean
  607. public SecurityFilterChain filterChain(HttpSecurity http) {
  608. http
  609. .sessionManagement((session) - session
  610. .sessionFixation((sessionFixation) -> sessionFixation
  611. .newSession()
  612. )
  613. );
  614. return http.build();
  615. }
  616. ----
  617. .Kotlin
  618. [source,kotlin,role="secondary"]
  619. ----
  620. @Bean
  621. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  622. http {
  623. sessionManagement {
  624. sessionFixation {
  625. newSession()
  626. }
  627. }
  628. }
  629. return http.build()
  630. }
  631. ----
  632. .XML
  633. [source,xml,role="secondary"]
  634. ----
  635. <http>
  636. <session-management session-fixation-protection="newSession" />
  637. </http>
  638. ----
  639. ====
  640. When session fixation protection occurs, it results in a `SessionFixationProtectionEvent` being published in the application context.
  641. If you use `changeSessionId`, this protection will __also__ result in any ``jakarta.servlet.http.HttpSessionIdListener``s being notified, so use caution if your code listens for both events.
  642. You can also set the session fixation protection to `none` to disable it, but this is not recommended as it leaves your application vulnerable.
  643. [[use-securitycontextholderstrategy]]
  644. == Using `SecurityContextHolderStrategy`
  645. Consider the following block of code:
  646. ====
  647. .Java
  648. [source,java,role="primary"]
  649. ----
  650. UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
  651. loginRequest.getUsername(), loginRequest.getPassword());
  652. Authentication authentication = this.authenticationManager.authenticate(token);
  653. // ...
  654. SecurityContext context = SecurityContextHolder.createEmptyContext(); <1>
  655. context.setAuthentication(authentication); <2>
  656. SecurityContextHolder.setContext(context); <3>
  657. ----
  658. ====
  659. 1. Creates an empty `SecurityContext` instance by accessing the `SecurityContextHolder` statically.
  660. 2. Sets the `Authentication` object in the `SecurityContext` instance.
  661. 3. Sets the `SecurityContext` instance in the `SecurityContextHolder` statically.
  662. While the above code works fine, it can produce some undesired effects: when components access the `SecurityContext` statically through `SecurityContextHolder`, this can create race conditions when there are multiple application contexts that want to specify the `SecurityContextHolderStrategy`.
  663. This is because in `SecurityContextHolder` there is one strategy per classloader instead of one per application context.
  664. To address this, components can wire `SecurityContextHolderStrategy` from the application context.
  665. By default, they will still look up the strategy from `SecurityContextHolder`.
  666. These changes are largely internal, but they present the opportunity for applications to autowire the `SecurityContextHolderStrategy` instead of accessing the `SecurityContext` statically.
  667. To do so, you should change the code to the following:
  668. ====
  669. .Java
  670. [source,java,role="primary"]
  671. ----
  672. public class SomeClass {
  673. private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
  674. public void someMethod() {
  675. UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(
  676. loginRequest.getUsername(), loginRequest.getPassword());
  677. Authentication authentication = this.authenticationManager.authenticate(token);
  678. // ...
  679. SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); <1>
  680. context.setAuthentication(authentication); <2>
  681. this.securityContextHolderStrategy.setContext(context); <3>
  682. }
  683. }
  684. ----
  685. ====
  686. 1. Creates an empty `SecurityContext` instance using the configured `SecurityContextHolderStrategy`.
  687. 2. Sets the `Authentication` object in the `SecurityContext` instance.
  688. 3. Sets the `SecurityContext` instance in the `SecurityContextHolderStrategy`.
  689. [[session-mgmt-force-session-creation]]
  690. == Forcing Eager Session Creation
  691. At times, it can be valuable to eagerly create sessions.
  692. This can be done by using the {security-api-url}org/springframework/security/web/session/ForceEagerSessionCreationFilter.html[`ForceEagerSessionCreationFilter`] which can be configured using:
  693. ====
  694. .Java
  695. [source,java,role="primary"]
  696. ----
  697. @Bean
  698. public SecurityFilterChain filterChain(HttpSecurity http) {
  699. http
  700. .sessionManagement(session -> session
  701. .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
  702. );
  703. return http.build();
  704. }
  705. ----
  706. .Kotlin
  707. [source,kotlin,role="secondary"]
  708. ----
  709. @Bean
  710. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  711. http {
  712. sessionManagement {
  713. sessionCreationPolicy = SessionCreationPolicy.ALWAYS
  714. }
  715. }
  716. return http.build()
  717. }
  718. ----
  719. .XML
  720. [source,xml,role="secondary"]
  721. ----
  722. <http create-session="ALWAYS">
  723. </http>
  724. ----
  725. ====
  726. == What to read next
  727. - Clustered sessions with https://docs.spring.io/spring-session/reference/index.html[Spring Session]