logout.adoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. = OIDC Logout
  2. Once an end user is able to login to your application, it's important to consider how they will log out.
  3. Generally speaking, there are three use cases for you to consider:
  4. 1. I want to perform only a local logout
  5. 2. I want to log out both my application and the OIDC Provider, initiated by my application
  6. 3. I want to log out both my application and the OIDC Provider, initiated by the OIDC Provider
  7. [[configure-local-logout]]
  8. == Local Logout
  9. To perform a local logout, no special OIDC configuration is needed.
  10. Spring Security automatically stands up a local logout endpoint, which you can xref:servlet/authentication/logout.adoc[configure through the `logout()` DSL].
  11. [[configure-client-initiated-oidc-logout]]
  12. == OpenID Connect 1.0 Client-Initiated Logout
  13. OpenID Connect Session Management 1.0 allows the ability to log out the end user at the Provider by using the Client.
  14. One of the strategies available is https://openid.net/specs/openid-connect-rpinitiated-1_0.html[RP-Initiated Logout].
  15. If the OpenID Provider supports both Session Management and https://openid.net/specs/openid-connect-discovery-1_0.html[Discovery], the client can obtain the `end_session_endpoint` `URL` from the OpenID Provider's https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata[Discovery Metadata].
  16. You can do so by configuring the `ClientRegistration` with the `issuer-uri`, as follows:
  17. [source,yaml]
  18. ----
  19. spring:
  20. security:
  21. oauth2:
  22. client:
  23. registration:
  24. okta:
  25. client-id: okta-client-id
  26. client-secret: okta-client-secret
  27. ...
  28. provider:
  29. okta:
  30. issuer-uri: https://dev-1234.oktapreview.com
  31. ----
  32. Also, you should configure `OidcClientInitiatedLogoutSuccessHandler`, which implements RP-Initiated Logout, as follows:
  33. [tabs]
  34. ======
  35. Java::
  36. +
  37. [source,java,role="primary"]
  38. ----
  39. @Configuration
  40. @EnableWebSecurity
  41. public class OAuth2LoginSecurityConfig {
  42. @Autowired
  43. private ClientRegistrationRepository clientRegistrationRepository;
  44. @Bean
  45. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  46. http
  47. .authorizeHttpRequests(authorize -> authorize
  48. .anyRequest().authenticated()
  49. )
  50. .oauth2Login(withDefaults())
  51. .logout(logout -> logout
  52. .logoutSuccessHandler(oidcLogoutSuccessHandler())
  53. );
  54. return http.build();
  55. }
  56. private LogoutSuccessHandler oidcLogoutSuccessHandler() {
  57. OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler =
  58. new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);
  59. // Sets the location that the End-User's User Agent will be redirected to
  60. // after the logout has been performed at the Provider
  61. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
  62. return oidcLogoutSuccessHandler;
  63. }
  64. }
  65. ----
  66. Kotlin::
  67. +
  68. [source,kotlin,role="secondary"]
  69. ----
  70. @Configuration
  71. @EnableWebSecurity
  72. class OAuth2LoginSecurityConfig {
  73. @Autowired
  74. private lateinit var clientRegistrationRepository: ClientRegistrationRepository
  75. @Bean
  76. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  77. http {
  78. authorizeHttpRequests {
  79. authorize(anyRequest, authenticated)
  80. }
  81. oauth2Login { }
  82. logout {
  83. logoutSuccessHandler = oidcLogoutSuccessHandler()
  84. }
  85. }
  86. return http.build()
  87. }
  88. private fun oidcLogoutSuccessHandler(): LogoutSuccessHandler {
  89. val oidcLogoutSuccessHandler = OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository)
  90. // Sets the location that the End-User's User Agent will be redirected to
  91. // after the logout has been performed at the Provider
  92. oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}")
  93. return oidcLogoutSuccessHandler
  94. }
  95. }
  96. ----
  97. ======
  98. [NOTE]
  99. ====
  100. `OidcClientInitiatedLogoutSuccessHandler` supports the `+{baseUrl}+` placeholder.
  101. If used, the application's base URL, such as `https://app.example.org`, replaces it at request time.
  102. ====
  103. [[configure-provider-initiated-oidc-logout]]
  104. == OpenID Connect 1.0 Back-Channel Logout
  105. OpenID Connect Session Management 1.0 allows the ability to log out the end user at the Client by having the Provider make an API call to the Client.
  106. This is referred to as https://openid.net/specs/openid-connect-backchannel-1_0.html[OIDC Back-Channel Logout].
  107. To enable this, you can stand up the Back-Channel Logout endpoint in the DSL like so:
  108. [tabs]
  109. ======
  110. Java::
  111. +
  112. [source,java,role="primary"]
  113. ----
  114. @Bean
  115. OidcBackChannelLogoutHandler oidcLogoutHandler() {
  116. return new OidcBackChannelLogoutHandler();
  117. }
  118. @Bean
  119. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  120. http
  121. .authorizeHttpRequests((authorize) -> authorize
  122. .anyRequest().authenticated()
  123. )
  124. .oauth2Login(withDefaults())
  125. .oidcLogout((logout) -> logout
  126. .backChannel(Customizer.withDefaults())
  127. );
  128. return http.build();
  129. }
  130. ----
  131. Kotlin::
  132. +
  133. [source,kotlin,role="secondary"]
  134. ----
  135. @Bean
  136. fun oidcLogoutHandler(): OidcBackChannelLogoutHandler {
  137. return OidcBackChannelLogoutHandler()
  138. }
  139. @Bean
  140. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  141. http {
  142. authorizeRequests {
  143. authorize(anyRequest, authenticated)
  144. }
  145. oauth2Login { }
  146. oidcLogout {
  147. backChannel { }
  148. }
  149. }
  150. return http.build()
  151. }
  152. ----
  153. ======
  154. Then, you need a way listen to events published by Spring Security to remove old `OidcSessionInformation` entries, like so:
  155. [tabs]
  156. ======
  157. Java::
  158. +
  159. [source,java,role="primary"]
  160. ----
  161. @Bean
  162. public HttpSessionEventPublisher sessionEventPublisher() {
  163. return new HttpSessionEventPublisher();
  164. }
  165. ----
  166. Kotlin::
  167. +
  168. [source,kotlin,role="secondary"]
  169. ----
  170. @Bean
  171. open fun sessionEventPublisher(): HttpSessionEventPublisher {
  172. return HttpSessionEventPublisher()
  173. }
  174. ----
  175. ======
  176. This will make so that if `HttpSession#invalidate` is called, then the session is also removed from memory.
  177. And that's it!
  178. This will stand up the endpoint `+/logout/connect/back-channel/{registrationId}+` which the OIDC Provider can request to invalidate a given session of an end user in your application.
  179. [NOTE]
  180. `oidcLogout` requires that `oauth2Login` also be configured.
  181. [NOTE]
  182. `oidcLogout` requires that the session cookie be called `JSESSIONID` in order to correctly log out each session through a backchannel.
  183. === Back-Channel Logout Architecture
  184. Consider a `ClientRegistration` whose identifier is `registrationId`.
  185. The overall flow for a Back-Channel logout is like this:
  186. 1. At login time, Spring Security correlates the ID Token, CSRF Token, and Provider Session ID (if any) to your application's session id in its `OidcSessionRegistry` implementation.
  187. 2. Then at logout time, your OIDC Provider makes an API call to `/logout/connect/back-channel/registrationId` including a Logout Token that indicates either the `sub` (the End User) or the `sid` (the Provider Session ID) to logout.
  188. 3. Spring Security validates the token's signature and claims.
  189. 4. If the token contains a `sid` claim, then only the Client's session that correlates to that provider session is terminated.
  190. 5. Otherwise, if the token contains a `sub` claim, then all that Client's sessions for that End User are terminated.
  191. [NOTE]
  192. Remember that Spring Security's OIDC support is multi-tenant.
  193. This means that it will only terminate sessions whose Client matches the `aud` claim in the Logout Token.
  194. One notable part of this architecture's implementation is that it propagates the incoming back-channel request internally for each corresponding session.
  195. Initially, this may seem unnecessary.
  196. However, recall that the Servlet API does not give direct access to the `HttpSession` store.
  197. By making an internal logout call, the corresponding session can now be validated.
  198. Additionally, forging a logout call internally allows for each set of ``LogoutHandler``s to be run against that session and corresponding `SecurityContext`.
  199. === Customizing the Session Logout Endpoint
  200. With `OidcBackChannelLogoutHandler` published, the session logout endpoint is `+{baseUrl}+/logout/connect/back-channel/+{registrationId}+`.
  201. If `OidcBackChannelLogoutHandler` is not wired, then the URL is `+{baseUrl}+/logout/connect/back-channel/+{registrationId}+`, which is not recommended since it requires passing a CSRF token, which can be challenging depending on the kind of repository your application uses.
  202. In the event that you need to customize the endpoint, you can provide the URL as follows:
  203. [tabs]
  204. ======
  205. Java::
  206. +
  207. [source=java,role="primary"]
  208. ----
  209. http
  210. // ...
  211. .oidcLogout((oidc) -> oidc
  212. .backChannel((backChannel) -> backChannel
  213. .logoutUri("http://localhost:9000/logout/connect/back-channel/+{registrationId}+")
  214. )
  215. );
  216. ----
  217. Kotlin::
  218. +
  219. [source=kotlin,role="secondary"]
  220. ----
  221. http {
  222. oidcLogout {
  223. backChannel {
  224. logoutUri = "http://localhost:9000/logout/connect/back-channel/+{registrationId}+"
  225. }
  226. }
  227. }
  228. ----
  229. ======
  230. === Customizing the Session Logout Cookie Name
  231. By default, the session logout endpoint uses the `JSESSIONID` cookie to correlate the session to the corresponding `OidcSessionInformation`.
  232. However, the default cookie name in Spring Session is `SESSION`.
  233. You can configure Spring Session's cookie name in the DSL like so:
  234. [tabs]
  235. ======
  236. Java::
  237. +
  238. [source=java,role="primary"]
  239. ----
  240. @Bean
  241. OidcBackChannelLogoutHandler oidcLogoutHandler(OidcSessionRegistry sessionRegistry) {
  242. OidcBackChannelLogoutHandler logoutHandler = new OidcBackChannelLogoutHandler(oidcSessionRegistry);
  243. logoutHandler.setSessionCookieName("SESSION");
  244. return logoutHandler;
  245. }
  246. ----
  247. Kotlin::
  248. +
  249. [source=kotlin,role="secondary"]
  250. ----
  251. @Bean
  252. open fun oidcLogoutHandler(val sessionRegistry: OidcSessionRegistry): OidcBackChannelLogoutHandler {
  253. val logoutHandler = OidcBackChannelLogoutHandler(sessionRegistry)
  254. logoutHandler.setSessionCookieName("SESSION")
  255. return logoutHandler
  256. }
  257. ----
  258. ======
  259. [[oidc-backchannel-logout-session-registry]]
  260. === Customizing the OIDC Provider Session Registry
  261. By default, Spring Security stores in-memory all links between the OIDC Provider session and the Client session.
  262. There are a number of circumstances, like a clustered application, where it would be nice to store this instead in a separate location, like a database.
  263. You can achieve this by configuring a custom `OidcSessionRegistry`, like so:
  264. [tabs]
  265. ======
  266. Java::
  267. +
  268. [source,java,role="primary"]
  269. ----
  270. @Component
  271. public final class MySpringDataOidcSessionRegistry implements OidcSessionRegistry {
  272. private final OidcProviderSessionRepository sessions;
  273. // ...
  274. @Override
  275. public void saveSessionInformation(OidcSessionInformation info) {
  276. this.sessions.save(info);
  277. }
  278. @Override
  279. public OidcSessionInformation removeSessionInformation(String clientSessionId) {
  280. return this.sessions.removeByClientSessionId(clientSessionId);
  281. }
  282. @Override
  283. public Iterable<OidcSessionInformation> removeSessionInformation(OidcLogoutToken token) {
  284. return token.getSessionId() != null ?
  285. this.sessions.removeBySessionIdAndIssuerAndAudience(...) :
  286. this.sessions.removeBySubjectAndIssuerAndAudience(...);
  287. }
  288. }
  289. ----
  290. Kotlin::
  291. +
  292. [source,kotlin,role="secondary"]
  293. ----
  294. @Component
  295. class MySpringDataOidcSessionRegistry: OidcSessionRegistry {
  296. val sessions: OidcProviderSessionRepository
  297. // ...
  298. @Override
  299. fun saveSessionInformation(info: OidcSessionInformation) {
  300. this.sessions.save(info)
  301. }
  302. @Override
  303. fun removeSessionInformation(clientSessionId: String): OidcSessionInformation {
  304. return this.sessions.removeByClientSessionId(clientSessionId);
  305. }
  306. @Override
  307. fun removeSessionInformation(token: OidcLogoutToken): Iterable<OidcSessionInformation> {
  308. return token.getSessionId() != null ?
  309. this.sessions.removeBySessionIdAndIssuerAndAudience(...) :
  310. this.sessions.removeBySubjectAndIssuerAndAudience(...);
  311. }
  312. }
  313. ----
  314. ======