session-management.adoc 34 KB

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