concurrent-sessions-control.adoc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. [[reactive-concurrent-sessions-control]]
  2. = Concurrent Sessions Control
  3. Similar to xref:servlet/authentication/session-management.adoc#ns-concurrent-sessions[Servlet's Concurrent Sessions Control], Spring Security also provides support to limit the number of concurrent sessions a user can have in a Reactive application.
  4. When you set up Concurrent Sessions Control in Spring Security, it monitors authentications carried out through Form Login, xref:reactive/oauth2/login/index.adoc[OAuth 2.0 Login], and HTTP Basic authentication by hooking into the way those authentication mechanisms handle authentication success.
  5. More specifically, the session management DSL will add the {security-api-url}org/springframework/security/web/server/authentication/ConcurrentSessionControlServerAuthenticationSuccessHandler.html[ConcurrentSessionControlServerAuthenticationSuccessHandler] and the {security-api-url}org/springframework/security/web/server/authentication/RegisterSessionServerAuthenticationSuccessHandler.html[RegisterSessionServerAuthenticationSuccessHandler] to the list of `ServerAuthenticationSuccessHandler` used by the authentication filter.
  6. The following sections contains examples of how to configure Concurrent Sessions Control.
  7. * <<reactive-concurrent-sessions-control-limit,I want to limit the number of concurrent sessions a user can have>>
  8. * <<concurrent-sessions-control-custom-strategy,I want to customize the strategy used when the maximum number of sessions is exceeded>>
  9. * <<reactive-concurrent-sessions-control-specify-session-registry,I want to know how to specify a `ReactiveSessionRegistry`>>
  10. * <<concurrent-sessions-control-sample,I want to see a sample application that uses Concurrent Sessions Control>>
  11. * <<disabling-for-authentication-filters,I want to know how to disable it for some authentication filter>>
  12. [[reactive-concurrent-sessions-control-limit]]
  13. == Limiting Concurrent Sessions
  14. By default, Spring Security will allow any number of concurrent sessions for a user.
  15. To limit the number of concurrent sessions, you can use the `maximumSessions` DSL method:
  16. .Configuring one session for any user
  17. [tabs]
  18. ======
  19. Java::
  20. +
  21. [source,java,role="primary"]
  22. ----
  23. @Bean
  24. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  25. http
  26. // ...
  27. .sessionManagement((sessions) -> sessions
  28. .concurrentSessions((concurrency) -> concurrency
  29. .maximumSessions(SessionLimit.of(1))
  30. )
  31. );
  32. return http.build();
  33. }
  34. @Bean
  35. ReactiveSessionRegistry reactiveSessionRegistry() {
  36. return new InMemoryReactiveSessionRegistry();
  37. }
  38. ----
  39. Kotlin::
  40. +
  41. [source,kotlin,role="secondary"]
  42. ----
  43. @Bean
  44. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  45. return http {
  46. // ...
  47. sessionManagement {
  48. sessionConcurrency {
  49. maximumSessions = SessionLimit.of(1)
  50. }
  51. }
  52. }
  53. }
  54. @Bean
  55. open fun reactiveSessionRegistry(): ReactiveSessionRegistry {
  56. return InMemoryReactiveSessionRegistry()
  57. }
  58. ----
  59. ======
  60. The above configuration allows one session for any user.
  61. Similarly, you can also allow unlimited sessions by using the `SessionLimit#UNLIMITED` constant:
  62. .Configuring unlimited sessions
  63. [tabs]
  64. ======
  65. Java::
  66. +
  67. [source,java,role="primary"]
  68. ----
  69. @Bean
  70. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  71. http
  72. // ...
  73. .sessionManagement((sessions) -> sessions
  74. .concurrentSessions((concurrency) -> concurrency
  75. .maximumSessions(SessionLimit.UNLIMITED))
  76. );
  77. return http.build();
  78. }
  79. @Bean
  80. ReactiveSessionRegistry reactiveSessionRegistry() {
  81. return new InMemoryReactiveSessionRegistry();
  82. }
  83. ----
  84. Kotlin::
  85. +
  86. [source,kotlin,role="secondary"]
  87. ----
  88. @Bean
  89. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  90. return http {
  91. // ...
  92. sessionManagement {
  93. sessionConcurrency {
  94. maximumSessions = SessionLimit.UNLIMITED
  95. }
  96. }
  97. }
  98. }
  99. @Bean
  100. open fun reactiveSessionRegistry(webSessionManager: WebSessionManager): ReactiveSessionRegistry {
  101. return InMemoryReactiveSessionRegistry()
  102. }
  103. ----
  104. ======
  105. Since the `maximumSessions` method accepts a `SessionLimit` interface, which in turn extends `Function<Authentication, Mono<Integer>>`, you can have a more complex logic to determine the maximum number of sessions based on the user's authentication:
  106. .Configuring maximumSessions based on `Authentication`
  107. [tabs]
  108. ======
  109. Java::
  110. +
  111. [source,java,role="primary"]
  112. ----
  113. @Bean
  114. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  115. http
  116. // ...
  117. .sessionManagement((sessions) -> sessions
  118. .concurrentSessions((concurrency) -> concurrency
  119. .maximumSessions(maxSessions()))
  120. );
  121. return http.build();
  122. }
  123. private SessionLimit maxSessions() {
  124. return (authentication) -> {
  125. if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_UNLIMITED_SESSIONS"))) {
  126. return Mono.empty(); // allow unlimited sessions for users with ROLE_UNLIMITED_SESSIONS
  127. }
  128. if (authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
  129. return Mono.just(2); // allow two sessions for admins
  130. }
  131. return Mono.just(1); // allow one session for every other user
  132. };
  133. }
  134. @Bean
  135. ReactiveSessionRegistry reactiveSessionRegistry() {
  136. return new InMemoryReactiveSessionRegistry();
  137. }
  138. ----
  139. Kotlin::
  140. +
  141. [source,kotlin,role="secondary"]
  142. ----
  143. @Bean
  144. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  145. return http {
  146. // ...
  147. sessionManagement {
  148. sessionConcurrency {
  149. maximumSessions = maxSessions()
  150. }
  151. }
  152. }
  153. }
  154. fun maxSessions(): SessionLimit {
  155. return { authentication ->
  156. if (authentication.authorities.contains(SimpleGrantedAuthority("ROLE_UNLIMITED_SESSIONS"))) Mono.empty
  157. if (authentication.authorities.contains(SimpleGrantedAuthority("ROLE_ADMIN"))) Mono.just(2)
  158. Mono.just(1)
  159. }
  160. }
  161. @Bean
  162. open fun reactiveSessionRegistry(): ReactiveSessionRegistry {
  163. return InMemoryReactiveSessionRegistry()
  164. }
  165. ----
  166. ======
  167. When the maximum number of sessions is exceeded, by default, the least recently used session(s) will be expired.
  168. If you want to change that behavior, you can <<concurrent-sessions-control-custom-strategy,customize the strategy used when the maximum number of sessions is exceeded>>.
  169. [[concurrent-sessions-control-custom-strategy]]
  170. == Handling Maximum Number of Sessions Exceeded
  171. By default, when the maximum number of sessions is exceeded, the least recently used session(s) will be expired by using the {security-api-url}org/springframework/security/web/server/authentication/session/InvalidateLeastUsedMaximumSessionsExceededHandler.html[InvalidateLeastUsedMaximumSessionsExceededHandler].
  172. Spring Security also provides another implementation that prevents the user from creating new sessions by using the {security-api-url}org/springframework/security/web/server/authentication/session/PreventLoginMaximumSessionsExceededHandler.html[PreventLoginMaximumSessionsExceededHandler].
  173. If you want to use your own strategy, you can provide a different implementation of {security-api-url}org/springframework/security/web/server/authentication/session/ServerMaximumSessionsExceededHandler.html[ServerMaximumSessionsExceededHandler].
  174. .Configuring maximumSessionsExceededHandler
  175. [tabs]
  176. ======
  177. Java::
  178. +
  179. [source,java,role="primary"]
  180. ----
  181. @Bean
  182. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  183. http
  184. // ...
  185. .sessionManagement((sessions) -> sessions
  186. .concurrentSessions((concurrency) -> concurrency
  187. .maximumSessions(SessionLimit.of(1))
  188. .maximumSessionsExceededHandler(new PreventLoginMaximumSessionsExceededHandler())
  189. )
  190. );
  191. return http.build();
  192. }
  193. @Bean
  194. ReactiveSessionRegistry reactiveSessionRegistry() {
  195. return new InMemoryReactiveSessionRegistry();
  196. }
  197. ----
  198. Kotlin::
  199. +
  200. [source,kotlin,role="secondary"]
  201. ----
  202. @Bean
  203. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  204. return http {
  205. // ...
  206. sessionManagement {
  207. sessionConcurrency {
  208. maximumSessions = SessionLimit.of(1)
  209. maximumSessionsExceededHandler = PreventLoginMaximumSessionsExceededHandler()
  210. }
  211. }
  212. }
  213. }
  214. @Bean
  215. open fun reactiveSessionRegistry(): ReactiveSessionRegistry {
  216. return InMemoryReactiveSessionRegistry()
  217. }
  218. ----
  219. ======
  220. [[reactive-concurrent-sessions-control-specify-session-registry]]
  221. == Specifying a `ReactiveSessionRegistry`
  222. In order to keep track of the user's sessions, Spring Security uses a {security-api-url}org/springframework/security/core/session/ReactiveSessionRegistry.html[ReactiveSessionRegistry], and, every time a user logs in, their session information is saved.
  223. Spring Security ships with {security-api-url}org/springframework/security/core/session/InMemoryReactiveSessionRegistry.html[InMemoryReactiveSessionRegistry] implementation of `ReactiveSessionRegistry`.
  224. To specify a `ReactiveSessionRegistry` implementation you can either declare it as a bean:
  225. .ReactiveSessionRegistry as a Bean
  226. [tabs]
  227. ======
  228. Java::
  229. +
  230. [source,java,role="primary"]
  231. ----
  232. @Bean
  233. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  234. http
  235. // ...
  236. .sessionManagement((sessions) -> sessions
  237. .concurrentSessions((concurrency) -> concurrency
  238. .maximumSessions(SessionLimit.of(1))
  239. )
  240. );
  241. return http.build();
  242. }
  243. @Bean
  244. ReactiveSessionRegistry reactiveSessionRegistry() {
  245. return new MyReactiveSessionRegistry();
  246. }
  247. ----
  248. Kotlin::
  249. +
  250. [source,kotlin,role="secondary"]
  251. ----
  252. @Bean
  253. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  254. return http {
  255. // ...
  256. sessionManagement {
  257. sessionConcurrency {
  258. maximumSessions = SessionLimit.of(1)
  259. }
  260. }
  261. }
  262. }
  263. @Bean
  264. open fun reactiveSessionRegistry(): ReactiveSessionRegistry {
  265. return MyReactiveSessionRegistry()
  266. }
  267. ----
  268. ======
  269. or you can use the `sessionRegistry` DSL method:
  270. .ReactiveSessionRegistry using sessionRegistry DSL method
  271. [tabs]
  272. ======
  273. Java::
  274. +
  275. [source,java,role="primary"]
  276. ----
  277. @Bean
  278. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  279. http
  280. // ...
  281. .sessionManagement((sessions) -> sessions
  282. .concurrentSessions((concurrency) -> concurrency
  283. .maximumSessions(SessionLimit.of(1))
  284. .sessionRegistry(new MyReactiveSessionRegistry())
  285. )
  286. );
  287. return http.build();
  288. }
  289. ----
  290. Kotlin::
  291. +
  292. [source,kotlin,role="secondary"]
  293. ----
  294. @Bean
  295. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  296. return http {
  297. // ...
  298. sessionManagement {
  299. sessionConcurrency {
  300. maximumSessions = SessionLimit.of(1)
  301. sessionRegistry = MyReactiveSessionRegistry()
  302. }
  303. }
  304. }
  305. }
  306. ----
  307. ======
  308. [[reactive-concurrent-sessions-control-manually-invalidating-sessions]]
  309. == Invalidating Registered User's Sessions
  310. At times, it is handy to be able to invalidate all or some of a user's sessions.
  311. For example, when a user changes their password, you may want to invalidate all of their sessions so that they are forced to log in again.
  312. To do that, you can use the `ReactiveSessionRegistry` bean to retrieve all the user's sessions, invalidate them, and them remove them from the `WebSessionStore`:
  313. .Using ReactiveSessionRegistry to invalidate sessions manually
  314. [tabs]
  315. ======
  316. Java::
  317. +
  318. [source,java,role="primary"]
  319. ----
  320. public class SessionControl {
  321. private final ReactiveSessionRegistry reactiveSessionRegistry;
  322. private final WebSessionStore webSessionStore;
  323. public Mono<Void> invalidateSessions(String username) {
  324. return this.reactiveSessionRegistry.getAllSessions(username)
  325. .flatMap((session) -> session.invalidate().thenReturn(session))
  326. .flatMap((session) -> this.webSessionStore.removeSession(session.getSessionId()))
  327. .then();
  328. }
  329. }
  330. ----
  331. ======
  332. [[disabling-for-authentication-filters]]
  333. == Disabling It for Some Authentication Filters
  334. By default, Concurrent Sessions Control will be configured automatically for Form Login, OAuth 2.0 Login, and HTTP Basic authentication as long as they do not specify an `ServerAuthenticationSuccessHandler` themselves.
  335. For example, the following configuration will disable Concurrent Sessions Control for Form Login:
  336. .Disabling Concurrent Sessions Control for Form Login
  337. [tabs]
  338. ======
  339. Java::
  340. +
  341. [source,java,role="primary"]
  342. ----
  343. @Bean
  344. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  345. http
  346. // ...
  347. .formLogin((login) -> login
  348. .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/"))
  349. )
  350. .sessionManagement((sessions) -> sessions
  351. .concurrentSessions((concurrency) -> concurrency
  352. .maximumSessions(SessionLimit.of(1))
  353. )
  354. );
  355. return http.build();
  356. }
  357. ----
  358. Kotlin::
  359. +
  360. [source,kotlin,role="secondary"]
  361. ----
  362. @Bean
  363. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  364. return http {
  365. // ...
  366. formLogin {
  367. authenticationSuccessHandler = RedirectServerAuthenticationSuccessHandler("/")
  368. }
  369. sessionManagement {
  370. sessionConcurrency {
  371. maximumSessions = SessionLimit.of(1)
  372. }
  373. }
  374. }
  375. }
  376. ----
  377. ======
  378. === Adding Additional Success Handlers Without Disabling Concurrent Sessions Control
  379. You can also include additional `ServerAuthenticationSuccessHandler` instances to the list of handlers used by the authentication filter without disabling Concurrent Sessions Control.
  380. To do that you can use the `authenticationSuccessHandler(Consumer<List<ServerAuthenticationSuccessHandler>>)` method:
  381. .Adding additional handlers
  382. [tabs]
  383. ======
  384. Java::
  385. +
  386. [source,java,role="primary"]
  387. ----
  388. @Bean
  389. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  390. http
  391. // ...
  392. .formLogin((login) -> login
  393. .authenticationSuccessHandler((handlers) -> handlers.add(new MyAuthenticationSuccessHandler()))
  394. )
  395. .sessionManagement((sessions) -> sessions
  396. .concurrentSessions((concurrency) -> concurrency
  397. .maximumSessions(SessionLimit.of(1))
  398. )
  399. );
  400. return http.build();
  401. }
  402. ----
  403. ======
  404. [[concurrent-sessions-control-sample]]
  405. == Checking a Sample Application
  406. You can check the {gh-samples-url}/reactive/webflux/java/session-management/maximum-sessions[sample application here].