logout.adoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. [[jc-logout]]
  2. = Handling Logouts
  3. In an application where end users can xref:servlet/authentication/index.adoc[login], they should also be able to logout.
  4. By default, Spring Security stands up a `/logout` endpoint, so no additional code is necessary.
  5. The rest of this section covers a number of use cases for you to consider:
  6. * I want to <<logout-java-configuration,understand logout's architecture>>
  7. * I want to <<customizing-logout-uris, customize the logout or logout success URI>>
  8. * I want to know when I need to <<permit-logout-endpoints, explicitly permit the `/logout` endpoint>>
  9. * I want to <<clear-all-site-data, clear cookies, storage, and/or cache>> when the user logs out
  10. * I am using OAuth 2.0 and I want to xref:servlet/oauth2/login/advanced.adoc#oauth2login-advanced-oidc-logout[coordinate logout with an Authorization Server]
  11. * I am using SAML 2.0 and I want to xref:servlet/saml2/logout.adoc[coordinate logout with an Identity Provider]
  12. * I am using CAS and I want to xref:servlet/authentication/cas.adoc#cas-singlelogout[coordinate logout with an Identity Provider]
  13. [[logout-architecture]]
  14. [[logout-java-configuration]]
  15. == Understanding Logout's Architecture
  16. When you include {spring-boot-reference-url}using.html#using.build-systems.starters[the `spring-boot-starter-security` dependency] or use the `@EnableWebSecurity` annotation, Spring Security will add its logout support and by default respond both to `GET /logout` and `POST /logout`.
  17. If you request `GET /logout`, then Spring Security displays a logout confirmation page.
  18. Aside from providing a valuable double-checking mechanism for the user, it also provides a simple way to provide xref:servlet/exploits/csrf.adoc[the needed CSRF token] to `POST /logout`.
  19. [TIP]
  20. In your application it is not necessary to use `GET /logout` to perform a logout.
  21. So long as xref:servlet/exploits/csrf.adoc[the needed CSRF token] is present in the request, your application can simply `POST /logout` to induce a logout.
  22. If you request `POST /logout`, then it will perform the following default operations using a series of {security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[``LogoutHandler``]s:
  23. - Invalidate the HTTP session ({security-api-url}org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[`SecurityContextLogoutHandler`])
  24. - Clear the xref:servlet/authentication/session-management.adoc#use-securitycontextholderstrategy[`SecurityContextHolderStrategy`] ({security-api-url}org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[`SecurityContextLogoutHandler`])
  25. - Clear the xref:servlet/authentication/persistence.adoc#securitycontextrepository[`SecurityContextRepository`] ({security-api-url}org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[`SecurityContextLogoutHandler`])
  26. - Clean up any xref:servlet/authentication/rememberme.adoc[RememberMe authentication] (`TokenRememberMeServices` / `PersistentTokenRememberMeServices`)
  27. - Clear out any saved xref:servlet/exploits/csrf.adoc[CSRF token] ({security-api-url}org/springframework/security/web/csrf/CsrfLogoutHandler.html[`CsrfLogoutHandler`])
  28. - xref:servlet/authentication/events.adoc[Fire] a `LogoutSuccessEvent` ({security-api-url}org/springframework/security/web/authentication/logout/LogoutSuccessEventPublishingLogoutHandler.html[`LogoutSuccessEventPublishingLogoutHandler`])
  29. Once completed, then it will exercise its default {security-api-url}org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html[`LogoutSuccessHandler`] which redirects to `/login?logout`.
  30. [[customizing-logout-uris]]
  31. == Customizing Logout URIs
  32. Since the `LogoutFilter` appears before xref:servlet/authorization/authorize-http-requests.adoc[the `AuthorizationFilter`] in xref:servlet/architecture.adoc#servlet-filterchain-figure[the filter chain], it is not necessary by default to explicitly permit the `/logout` endpoint.
  33. Thus, only <<permit-logout-endpoints,custom logout endpoints>> that you create yourself generally require a `permitAll` configuration to be reachable.
  34. For example, if you want to simply change the URI that Spring Security is matching, you can do so in the `logout` DSL in following way:
  35. .Custom Logout Uri
  36. ====
  37. .Java
  38. [source,java,role="primary"]
  39. ----
  40. http
  41. .logout((logout) -> logout.logoutUrl("/my/logout/uri"))
  42. ----
  43. .Kotlin
  44. [source,kotlin,role="secondary"]
  45. ----
  46. http {
  47. logout {
  48. logoutUrl = "/my/logout/uri"
  49. }
  50. }
  51. ----
  52. .Xml
  53. [source,xml,role="secondary"]
  54. ----
  55. <logout logout-url="/my/logout/uri"/>
  56. ----
  57. ====
  58. and no authorization changes are necessary since it simply adjusts the `LogoutFilter`.
  59. [[permit-logout-endpoints]]
  60. However, if you stand up your own logout success endpoint (or in a rare case, <<creating-custom-logout-endpoint, your own logout endpoint>>), say using {spring-framework-reference-url}web.html#spring-web[Spring MVC], you will need permit it in Spring Security.
  61. This is because Spring MVC processes your request after Spring Security does.
  62. You can do this using `authorizeHttpRequests` or `<intercept-url>` like so:
  63. .Custom Logout Endpoint
  64. ====
  65. .Java
  66. [source,java,role="primary"]
  67. ----
  68. http
  69. .authorizeHttpRequests((authorize) -> authorize
  70. .requestMatchers("/my/success/endpoint").permitAll()
  71. // ...
  72. )
  73. .logout((logout) -> logout.logoutSuccessUrl("/my/success/endpoint"))
  74. ----
  75. .Kotlin
  76. [source,kotlin,role="secondary"]
  77. ----
  78. http {
  79. authorizeHttpRequests {
  80. authorize("/my/success/endpoint", permitAll)
  81. }
  82. logout {
  83. logoutSuccessUrl = "/my/success/endpoint"
  84. }
  85. }
  86. ----
  87. .Xml
  88. [source,xml,role="secondary"]
  89. ----
  90. <http>
  91. <filter-url pattern="/my/success/endpoint" access="permitAll"/>
  92. <logout logout-success-url="/my/success/endpoint"/>
  93. </http>
  94. ----
  95. ====
  96. In this example, you tell the `LogoutFilter` to redirect to `/my/success/endpoint` when it is done.
  97. And, you explicitly permit the `/my/success/endpoint` endpoint in xref:servlet/authorization/authorize-http-requests.adoc[the `AuthorizationFilter`].
  98. Specifying it twice can be cumbersome, though.
  99. If you are using Java configuration, you can instead set the `permitAll` property in the logout DSL like so:
  100. .Permitting Custom Logout Endpoints
  101. ====
  102. .Java
  103. [source,java,role="primary"]
  104. ----
  105. http
  106. .authorizeHttpRequests((authorize) -> authorize
  107. // ...
  108. )
  109. .logout((logout) -> logout
  110. .logoutSuccessUrl("/my/success/endpoint")
  111. .permitAll()
  112. )
  113. ----
  114. .Kotlin
  115. [source,kotlin,role="secondary"]
  116. ----
  117. http
  118. authorizeHttpRequests {
  119. // ...
  120. }
  121. logout {
  122. logoutSuccessUrl = "/my/success/endpoint"
  123. permitAll = true
  124. }
  125. ----
  126. ====
  127. which will add all logout URIs to the permit list for you.
  128. [[add-logout-handler]]
  129. == Adding Clean-up Actions
  130. If you are using Java configuration, you can add clean up actions of your own by calling the `addLogoutHandler` method in the `logout` DSL, like so:
  131. .Custom Logout Handler
  132. ====
  133. .Java
  134. [source,java,role="primary"]
  135. ----
  136. CookieClearingLogoutHandler cookies = new CookieClearingLogoutHandler("our-custom-cookie");
  137. http
  138. .logout((logout) -> logout.addLogoutHandler(cookies))
  139. ----
  140. .Kotlin
  141. [source,kotlin,role="secondary"]
  142. ----
  143. http {
  144. logout {
  145. addLogoutHandler(CookieClearingLogoutHandler("our-custom-cookie"))
  146. }
  147. }
  148. ----
  149. ====
  150. [NOTE]
  151. Because {security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[``LogoutHandler``]s are for the purposes of cleanup, they should not throw exceptions.
  152. [TIP]
  153. Since {security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[`LogoutHandler`] is a functional interface, you can provide a custom one as a lambda.
  154. Some logout handler configurations are common enough that they are exposed directly in the `logout` DSL and `<logout>` element.
  155. One example is configuring session invalidation and another is which additional cookies should be deleted.
  156. For example, you can configure the {security-api-url}org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.html[`CookieClearingLogoutHandler`] as seen above.
  157. [[delete-cookies]]
  158. Or you can instead set the appropriate configuration value like so:
  159. ====
  160. .Java
  161. [source,java,role="primary"]
  162. ----
  163. http
  164. .logout((logout) -> logout.deleteCookies("our-custom-cookie"))
  165. ----
  166. .Kotlin
  167. [source,kotlin,role="secondary"]
  168. ----
  169. http {
  170. logout {
  171. deleteCookies = "our-custom-cookie"
  172. }
  173. }
  174. ----
  175. .Xml
  176. [source,kotlin,role="secondary"]
  177. ----
  178. <http>
  179. <logout delete-cookies="our-custom-cookie"/>
  180. </http>
  181. ----
  182. ====
  183. [NOTE]
  184. Specifying that the `JSESSIONID` cookie is not necessary since {security-api-url}/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[`SecurityContextLogoutHandler`] removes it by virtue of invalidating the session.
  185. [[clear-all-site-data]]
  186. === Using Clear-Site-Data to Log Out the User
  187. The `Clear-Site-Data` HTTP header is one that browsers support as an instruction to clear cookies, storage, and cache that belong to the owning website.
  188. This is a handy and secure way to ensure that everything, including the session cookie, is cleaned up on logout.
  189. You can add configure Spring Security to write the `Clear-Site-Data` header on logout like so:
  190. .Using Clear-Site-Data
  191. ====
  192. .Java
  193. [source,java,role="primary"]
  194. ----
  195. HeaderWriterLogoutHandler clearSiteData = new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter());
  196. http
  197. .logout((logout) -> logout.addLogoutHandler(clearSiteData))
  198. ----
  199. .Kotlin
  200. [source,kotlin,role="secondary"]
  201. ----
  202. val clearSiteData = HeaderWriterLogoutHandler(ClearSiteDataHeaderWriter())
  203. http {
  204. logout {
  205. addLogoutHandler(clearSiteData)
  206. }
  207. }
  208. ----
  209. ====
  210. You give the `ClearSiteDataHeaderWriter` constructor the list of things that you want to be cleared out.
  211. The above configuration clears out all site data, but you can also configure it to remove just cookies like so:
  212. .Using Clear-Site-Data to Clear Cookies
  213. ====
  214. .Java
  215. [source,java,role="primary"]
  216. ----
  217. HeaderWriterLogoutHandler clearSiteData = new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(Directives.COOKIES));
  218. http
  219. .logout((logout) -> logout.addLogoutHandler(clearSiteData))
  220. ----
  221. .Kotlin
  222. [source,kotlin,role="secondary"]
  223. ----
  224. val clearSiteData = HeaderWriterLogoutHandler(ClearSiteDataHeaderWriter(Directives.COOKIES))
  225. http {
  226. logout {
  227. addLogoutHandler(clearSiteData)
  228. }
  229. }
  230. ----
  231. ====
  232. [[customizing-logout-success]]
  233. == Customizing Logout Success
  234. While using `logoutSuccessUrl` will suffice for most cases, you may need to do something different from redirecting to a URL once logout is complete.
  235. {security-api-url}org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html[`LogoutSuccessHandler`] is the Spring Security component for customizing logout success actions.
  236. For example, instead of redirecting, you may want to only return a status code.
  237. In this case, you can provide a success handler instance, like so:
  238. .Using Clear-Site-Data to Clear Cookies
  239. ====
  240. .Java
  241. [source,java,role="primary"]
  242. ----
  243. http
  244. .logout((logout) -> logout.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()))
  245. ----
  246. .Kotlin
  247. [source,kotlin,role="secondary"]
  248. ----
  249. http {
  250. logout {
  251. logoutSuccessHandler = HttpStatusReturningLogoutSuccessHandler()
  252. }
  253. }
  254. ----
  255. .Xml
  256. [source,xml,role="secondary"]
  257. ----
  258. <bean name="mySuccessHandlerBean" class="org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler"/>
  259. <http>
  260. <logout success-handler-ref="mySuccessHandlerBean"/>
  261. </http>
  262. ----
  263. ====
  264. [TIP]
  265. Since {security-api-url}org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html[`LogoutSuccessHandler`] is a functional interface, you can provide a custom one as a lambda.
  266. [[creating-custom-logout-endpoint]]
  267. == Creating a Custom Logout Endpoint
  268. It is strongly recommended that you use the provided `logout` DSL to configure logout.
  269. One reason is that its easy to forget to call the needed Spring Security components to ensure a proper and complete logout.
  270. In fact, it is often simpler to <<add-logout-handler, register a custom `LogoutHandler`>> than create a {spring-framework-reference-url}web.html#spring-web[Spring MVC] endpoint for performing logout.
  271. That said, if you find yourself in a circumstance where a custom logout endpoint is needed, like the following one:
  272. .Custom Logout Endpoint
  273. ====
  274. .Java
  275. [source,java,role="primary"]
  276. ----
  277. @PostMapping("/my/logout")
  278. public String performLogout() {
  279. // .. perform logout
  280. return "redirect:/home";
  281. }
  282. ----
  283. .Kotlin
  284. [source,kotlin,role="secondary"]
  285. ----
  286. @PostMapping("/my/logout")
  287. fun performLogout(): String {
  288. // .. perform logout
  289. return "redirect:/home"
  290. }
  291. ----
  292. ====
  293. then you will need to have that endpoint invoke Spring Security's {security-api-url}/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[`SecurityContextLogoutHandler`] to ensure a secure and complete logout.
  294. Something like the following is needed at a minimum:
  295. .Custom Logout Endpoint
  296. ====
  297. .Java
  298. [source,java,role="primary"]
  299. ----
  300. SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
  301. @PostMapping("/my/logout")
  302. public String performLogout(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
  303. // .. perform logout
  304. this.logoutHandler.doLogout(request, response, authentication);
  305. return "redirect:/home";
  306. }
  307. ----
  308. .Kotlin
  309. [source,kotlin,role="secondary"]
  310. ----
  311. val logoutHandler = SecurityContextLogoutHandler()
  312. @PostMapping("/my/logout")
  313. fun performLogout(val authentication: Authentication, val request: HttpServletRequest, val response: HttpServletResponse): String {
  314. // .. perform logout
  315. this.logoutHandler.doLogout(request, response, authentication)
  316. return "redirect:/home"
  317. }
  318. ----
  319. ====
  320. Such will clear out the {security-api-url}/org/springframework/security/core/context/SecurityContextHolderStrategy.html[`SecurityContextHolderStrategy`] and {security-api-url}/org/springframework/security/web/context/SecurityContextRepository.html[`SecurityContextRepository`] as needed.
  321. Also, you'll need to <<permit-logout-endpoints, explicitly permit the endpoint>>.
  322. [WARNING]
  323. Failing to call {security-api-url}/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[`SecurityContextLogoutHandler`] means that xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontext[the `SecurityContext`] could still be available on subsequent requests, meaning that the user is not actually logged out.
  324. [[testing-logout]]
  325. == Testing Logout
  326. Once you have logout configured you can test it using xref:servlet/test/mockmvc/logout.adoc[Spring Security's MockMvc support].
  327. [[jc-logout-references]]
  328. == Further Logout-Related References
  329. - xref:servlet/test/mockmvc/logout.adoc#test-logout[Testing Logout]
  330. - xref:servlet/integrations/servlet-api.adoc#servletapi-logout[HttpServletRequest.logout()]
  331. - xref:servlet/authentication/rememberme.adoc#remember-me-impls[Remember-Me Interfaces and Implementations]
  332. - xref:servlet/exploits/csrf.adoc#csrf-considerations-logout[Logging Out] in section CSRF Caveats
  333. - Section xref:servlet/authentication/cas.adoc#cas-singlelogout[Single Logout] (CAS protocol)
  334. - Documentation for the xref:servlet/appendix/namespace/http.adoc#nsa-logout[logout element] in the Spring Security XML Namespace section