concurrent-sessions-control.adoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 javadoc:org.springframework.security.web.server.authentication.ConcurrentSessionControlServerAuthenticationSuccessHandler[] and the javadoc:org.springframework.security.web.server.authentication.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. [IMPORTANT]
  170. ====
  171. The Concurrent Session Management is not aware if there is another session in some Identity Provider that you might use via xref:reactive/oauth2/login/index.adoc[OAuth 2 Login] for example.
  172. If you also need to invalidate the session against the Identity Provider you must <<concurrent-sessions-control-custom-strategy,include your own implementation of `ServerMaximumSessionsExceededHandler`>>.
  173. ====
  174. [[concurrent-sessions-control-custom-strategy]]
  175. == Handling Maximum Number of Sessions Exceeded
  176. By default, when the maximum number of sessions is exceeded, the least recently used session(s) will be expired by using the javadoc:org.springframework.security.web.server.authentication.InvalidateLeastUsedServerMaximumSessionsExceededHandler[].
  177. Spring Security also provides another implementation that prevents the user from creating new sessions by using the javadoc:org.springframework.security.web.server.authentication.PreventLoginServerMaximumSessionsExceededHandler[].
  178. If you want to use your own strategy, you can provide a different implementation of javadoc:org.springframework.security.web.server.authentication.ServerMaximumSessionsExceededHandler[].
  179. .Configuring maximumSessionsExceededHandler
  180. [tabs]
  181. ======
  182. Java::
  183. +
  184. [source,java,role="primary"]
  185. ----
  186. @Bean
  187. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  188. http
  189. // ...
  190. .sessionManagement((sessions) -> sessions
  191. .concurrentSessions((concurrency) -> concurrency
  192. .maximumSessions(SessionLimit.of(1))
  193. .maximumSessionsExceededHandler(new PreventLoginMaximumSessionsExceededHandler())
  194. )
  195. );
  196. return http.build();
  197. }
  198. @Bean
  199. ReactiveSessionRegistry reactiveSessionRegistry() {
  200. return new InMemoryReactiveSessionRegistry();
  201. }
  202. ----
  203. Kotlin::
  204. +
  205. [source,kotlin,role="secondary"]
  206. ----
  207. @Bean
  208. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  209. return http {
  210. // ...
  211. sessionManagement {
  212. sessionConcurrency {
  213. maximumSessions = SessionLimit.of(1)
  214. maximumSessionsExceededHandler = PreventLoginMaximumSessionsExceededHandler()
  215. }
  216. }
  217. }
  218. }
  219. @Bean
  220. open fun reactiveSessionRegistry(): ReactiveSessionRegistry {
  221. return InMemoryReactiveSessionRegistry()
  222. }
  223. ----
  224. ======
  225. [[reactive-concurrent-sessions-control-specify-session-registry]]
  226. == Specifying a `ReactiveSessionRegistry`
  227. In order to keep track of the user's sessions, Spring Security uses a javadoc:org.springframework.security.core.session.ReactiveSessionRegistry[], and, every time a user logs in, their session information is saved.
  228. Spring Security ships with javadoc:org.springframework.security.core.session.InMemoryReactiveSessionRegistry[] implementation of `ReactiveSessionRegistry`.
  229. To specify a `ReactiveSessionRegistry` implementation you can either declare it as a bean:
  230. .ReactiveSessionRegistry as a Bean
  231. [tabs]
  232. ======
  233. Java::
  234. +
  235. [source,java,role="primary"]
  236. ----
  237. @Bean
  238. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  239. http
  240. // ...
  241. .sessionManagement((sessions) -> sessions
  242. .concurrentSessions((concurrency) -> concurrency
  243. .maximumSessions(SessionLimit.of(1))
  244. )
  245. );
  246. return http.build();
  247. }
  248. @Bean
  249. ReactiveSessionRegistry reactiveSessionRegistry() {
  250. return new MyReactiveSessionRegistry();
  251. }
  252. ----
  253. Kotlin::
  254. +
  255. [source,kotlin,role="secondary"]
  256. ----
  257. @Bean
  258. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  259. return http {
  260. // ...
  261. sessionManagement {
  262. sessionConcurrency {
  263. maximumSessions = SessionLimit.of(1)
  264. }
  265. }
  266. }
  267. }
  268. @Bean
  269. open fun reactiveSessionRegistry(): ReactiveSessionRegistry {
  270. return MyReactiveSessionRegistry()
  271. }
  272. ----
  273. ======
  274. or you can use the `sessionRegistry` DSL method:
  275. .ReactiveSessionRegistry using sessionRegistry DSL method
  276. [tabs]
  277. ======
  278. Java::
  279. +
  280. [source,java,role="primary"]
  281. ----
  282. @Bean
  283. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  284. http
  285. // ...
  286. .sessionManagement((sessions) -> sessions
  287. .concurrentSessions((concurrency) -> concurrency
  288. .maximumSessions(SessionLimit.of(1))
  289. .sessionRegistry(new MyReactiveSessionRegistry())
  290. )
  291. );
  292. return http.build();
  293. }
  294. ----
  295. Kotlin::
  296. +
  297. [source,kotlin,role="secondary"]
  298. ----
  299. @Bean
  300. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  301. return http {
  302. // ...
  303. sessionManagement {
  304. sessionConcurrency {
  305. maximumSessions = SessionLimit.of(1)
  306. sessionRegistry = MyReactiveSessionRegistry()
  307. }
  308. }
  309. }
  310. }
  311. ----
  312. ======
  313. [[reactive-concurrent-sessions-control-manually-invalidating-sessions]]
  314. == Invalidating Registered User's Sessions
  315. At times, it is handy to be able to invalidate all or some of a user's sessions.
  316. 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.
  317. 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`:
  318. .Using ReactiveSessionRegistry to invalidate sessions manually
  319. [tabs]
  320. ======
  321. Java::
  322. +
  323. [source,java,role="primary"]
  324. ----
  325. public class SessionControl {
  326. private final ReactiveSessionRegistry reactiveSessionRegistry;
  327. private final WebSessionStore webSessionStore;
  328. public Mono<Void> invalidateSessions(String username) {
  329. return this.reactiveSessionRegistry.getAllSessions(username)
  330. .flatMap((session) -> session.invalidate().thenReturn(session))
  331. .flatMap((session) -> this.webSessionStore.removeSession(session.getSessionId()))
  332. .then();
  333. }
  334. }
  335. ----
  336. ======
  337. [[disabling-for-authentication-filters]]
  338. == Disabling It for Some Authentication Filters
  339. 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.
  340. For example, the following configuration will disable Concurrent Sessions Control for Form Login:
  341. .Disabling Concurrent Sessions Control for Form Login
  342. [tabs]
  343. ======
  344. Java::
  345. +
  346. [source,java,role="primary"]
  347. ----
  348. @Bean
  349. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  350. http
  351. // ...
  352. .formLogin((login) -> login
  353. .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/"))
  354. )
  355. .sessionManagement((sessions) -> sessions
  356. .concurrentSessions((concurrency) -> concurrency
  357. .maximumSessions(SessionLimit.of(1))
  358. )
  359. );
  360. return http.build();
  361. }
  362. ----
  363. Kotlin::
  364. +
  365. [source,kotlin,role="secondary"]
  366. ----
  367. @Bean
  368. open fun springSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  369. return http {
  370. // ...
  371. formLogin {
  372. authenticationSuccessHandler = RedirectServerAuthenticationSuccessHandler("/")
  373. }
  374. sessionManagement {
  375. sessionConcurrency {
  376. maximumSessions = SessionLimit.of(1)
  377. }
  378. }
  379. }
  380. }
  381. ----
  382. ======
  383. === Adding Additional Success Handlers Without Disabling Concurrent Sessions Control
  384. You can also include additional `ServerAuthenticationSuccessHandler` instances to the list of handlers used by the authentication filter without disabling Concurrent Sessions Control.
  385. To do that you can use the `authenticationSuccessHandler(Consumer<List<ServerAuthenticationSuccessHandler>>)` method:
  386. .Adding additional handlers
  387. [tabs]
  388. ======
  389. Java::
  390. +
  391. [source,java,role="primary"]
  392. ----
  393. @Bean
  394. SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
  395. http
  396. // ...
  397. .formLogin((login) -> login
  398. .authenticationSuccessHandler((handlers) -> handlers.add(new MyAuthenticationSuccessHandler()))
  399. )
  400. .sessionManagement((sessions) -> sessions
  401. .concurrentSessions((concurrency) -> concurrency
  402. .maximumSessions(SessionLimit.of(1))
  403. )
  404. );
  405. return http.build();
  406. }
  407. ----
  408. ======
  409. [[concurrent-sessions-control-sample]]
  410. == Checking a Sample Application
  411. You can check the {gh-samples-url}/reactive/webflux/java/session-management/maximum-sessions[sample application here].