2
0

csrf.adoc 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. [[servlet-csrf]]
  2. = Cross Site Request Forgery (CSRF)
  3. :figures: servlet/exploits
  4. In an application where end users can xref:servlet/authentication/index.adoc[log in], it is important to consider how to protect against xref:features/exploits/csrf.adoc#csrf[Cross Site Request Forgery (CSRF)].
  5. Spring Security protects against CSRF attacks by default for xref:features/exploits/csrf.adoc#csrf-protection-read-only[unsafe HTTP methods], such as a POST request, so no additional code is necessary.
  6. You can specify the default configuration explicitly using the following:
  7. [[csrf-configuration]]
  8. .Configure CSRF Protection
  9. [tabs]
  10. ======
  11. Java::
  12. +
  13. [source,java,role="primary"]
  14. ----
  15. @Configuration
  16. @EnableWebSecurity
  17. public class SecurityConfig {
  18. @Bean
  19. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  20. http
  21. // ...
  22. .csrf(Customizer.withDefaults());
  23. return http.build();
  24. }
  25. }
  26. ----
  27. Kotlin::
  28. +
  29. [source,kotlin,role="secondary"]
  30. ----
  31. import org.springframework.security.config.annotation.web.invoke
  32. @Configuration
  33. @EnableWebSecurity
  34. class SecurityConfig {
  35. @Bean
  36. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  37. http {
  38. // ...
  39. csrf { }
  40. }
  41. return http.build()
  42. }
  43. }
  44. ----
  45. XML::
  46. +
  47. [source,xml,role="secondary"]
  48. ----
  49. <http>
  50. <!-- ... -->
  51. <csrf/>
  52. </http>
  53. ----
  54. ======
  55. To learn more about CSRF protection for your application, consider the following use cases:
  56. * I want to <<csrf-components,understand CSRF protection's components>>
  57. * I need to <<migrating-to-spring-security-6,migrate an application from Spring Security 5 to 6>>
  58. * I want to <<csrf-token-repository-cookie,store the `CsrfToken` in a cookie>> instead of <<csrf-token-repository-httpsession,the session>>
  59. * I want to <<csrf-token-repository-custom,store the `CsrfToken` in a custom location>>
  60. * I want to <<deferred-csrf-token-opt-out,opt-out of deferred tokens>>
  61. * I want to <<csrf-token-request-handler-opt-out-of-breach,opt-out of BREACH protection>>
  62. * I need guidance integrating <<csrf-integration-form,Thymeleaf, JSPs or another view technology>> with the backend
  63. * I need guidance integrating <<csrf-integration-javascript,Angular or another JavaScript framework>> with the backend
  64. * I need guidance integrating <<csrf-integration-mobile,a mobile application or another client>> with the backend
  65. * I need guidance on <<csrf-access-denied-handler,handling errors>>
  66. * I want to <<csrf-testing,test CSRF protection>>
  67. * I need guidance on <<disable-csrf,disabling CSRF protection>>
  68. [[csrf-components]]
  69. == Understanding CSRF Protection's Components
  70. CSRF protection is provided by several components that are composed within the javadoc:org.springframework.security.web.csrf.CsrfFilter[]:
  71. .`CsrfFilter` Components
  72. [.invert-dark]
  73. image::{figures}/csrf.png[]
  74. CSRF protection is divided into two parts:
  75. 1. Make the javadoc:org.springframework.security.web.csrf.CsrfToken[] available to the application by delegating to the <<csrf-token-request-handler,`CsrfTokenRequestHandler`>>.
  76. 2. Determine if the request requires CSRF protection, load and validate the token, and <<csrf-access-denied-handler,handle `AccessDeniedException`>>.
  77. .`CsrfFilter` Processing
  78. [.invert-dark]
  79. image::{figures}/csrf-processing.png[]
  80. * image:{icondir}/number_1.png[] First, the javadoc:org.springframework.security.web.csrf.DeferredCsrfToken[] is loaded, which holds a reference to the <<csrf-token-repository,`CsrfTokenRepository`>> so that the persisted `CsrfToken` can be loaded later (in image:{icondir}/number_4.png[]).
  81. * image:{icondir}/number_2.png[] Second, a `Supplier<CsrfToken>` (created from `DeferredCsrfToken`) is given to the <<csrf-token-request-handler,`CsrfTokenRequestHandler`>>, which is responsible for populating a request attribute to make the `CsrfToken` available to the rest of the application.
  82. * image:{icondir}/number_3.png[] Next, the main CSRF protection processing begins and checks if the current request requires CSRF protection. If not required, the filter chain is continued and processing ends.
  83. * image:{icondir}/number_4.png[] If CSRF protection is required, the persisted `CsrfToken` is finally loaded from the `DeferredCsrfToken`.
  84. * image:{icondir}/number_5.png[] Continuing, the actual CSRF token provided by the client (if any) is resolved using the <<csrf-token-request-handler,`CsrfTokenRequestHandler`>>.
  85. * image:{icondir}/number_6.png[] The actual CSRF token is compared against the persisted `CsrfToken`. If valid, the filter chain is continued and processing ends.
  86. * image:{icondir}/number_7.png[] If the actual CSRF token is invalid (or missing), an `AccessDeniedException` is passed to the <<csrf-access-denied-handler,`AccessDeniedHandler`>> and processing ends.
  87. [[migrating-to-spring-security-6]]
  88. == Migrating to Spring Security 6
  89. When migrating from Spring Security 5 to 6, there are a few changes that may impact your application.
  90. The following is an overview of the aspects of CSRF protection that have changed in Spring Security 6:
  91. * Loading of the `CsrfToken` is now <<deferred-csrf-token,deferred by default>> to improve performance by no longer requiring the session to be loaded on every request.
  92. * The `CsrfToken` now includes <<csrf-token-request-handler-breach,randomness on every request by default>> to protect the CSRF token from a https://en.wikipedia.org/wiki/BREACH[BREACH] attack.
  93. [TIP]
  94. ====
  95. The changes in Spring Security 6 require additional configuration for single-page applications, and as such you may find the <<csrf-integration-javascript-spa>> section particularly useful.
  96. ====
  97. See the https://docs.spring.io/spring-security/reference/5.8/migration/servlet/exploits.html[Exploit Protection] section of the https://docs.spring.io/spring-security/reference/5.8/migration/index.html[Migration] chapter for more information on migrating a Spring Security 5 application.
  98. [[csrf-token-repository]]
  99. == Persisting the `CsrfToken`
  100. The `CsrfToken` is persisted using a `CsrfTokenRepository`.
  101. By default, the <<csrf-token-repository-httpsession,`HttpSessionCsrfTokenRepository`>> is used for storing tokens in a session.
  102. Spring Security also provides the <<csrf-token-repository-cookie,`CookieCsrfTokenRepository`>> for storing tokens in a cookie.
  103. You can also specify <<csrf-token-repository-custom,your own implementation>> to store tokens wherever you like.
  104. [[csrf-token-repository-httpsession]]
  105. === Using the `HttpSessionCsrfTokenRepository`
  106. By default, Spring Security stores the expected CSRF token in the `HttpSession` by using javadoc:org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository[], so no additional code is necessary.
  107. The `HttpSessionCsrfTokenRepository` reads the token from a session (whether in-memory, cache, or database). If you need to access the session attribute directly, please first configure the session attribute name using `HttpSessionCsrfTokenRepository#setSessionAttributeName`.
  108. You can specify the default configuration explicitly using the following configuration:
  109. [[csrf-token-repository-httpsession-configuration]]
  110. .Configure `HttpSessionCsrfTokenRepository`
  111. [tabs]
  112. ======
  113. Java::
  114. +
  115. [source,java,role="primary"]
  116. ----
  117. @Configuration
  118. @EnableWebSecurity
  119. public class SecurityConfig {
  120. @Bean
  121. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  122. http
  123. // ...
  124. .csrf((csrf) -> csrf
  125. .csrfTokenRepository(new HttpSessionCsrfTokenRepository())
  126. );
  127. return http.build();
  128. }
  129. }
  130. ----
  131. Kotlin::
  132. +
  133. [source,kotlin,role="secondary"]
  134. ----
  135. import org.springframework.security.config.annotation.web.invoke
  136. @Configuration
  137. @EnableWebSecurity
  138. class SecurityConfig {
  139. @Bean
  140. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  141. http {
  142. // ...
  143. csrf {
  144. csrfTokenRepository = HttpSessionCsrfTokenRepository()
  145. }
  146. }
  147. return http.build()
  148. }
  149. }
  150. ----
  151. XML::
  152. +
  153. [source,xml,role="secondary"]
  154. ----
  155. <http>
  156. <!-- ... -->
  157. <csrf token-repository-ref="tokenRepository"/>
  158. </http>
  159. <b:bean id="tokenRepository"
  160. class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository"/>
  161. ----
  162. ======
  163. [[csrf-token-repository-cookie]]
  164. === Using the `CookieCsrfTokenRepository`
  165. You can persist the `CsrfToken` in a cookie to <<csrf-integration-javascript,support a JavaScript-based application>> using the javadoc:org.springframework.security.web.csrf.CookieCsrfTokenRepository[].
  166. The `CookieCsrfTokenRepository` writes to a cookie named `XSRF-TOKEN` and reads it from an HTTP request header named `X-XSRF-TOKEN` or the request parameter `_csrf` by default.
  167. These defaults come from Angular and its predecessor https://docs.angularjs.org/api/ng/service/$http#cross-site-request-forgery-xsrf-protection[AngularJS].
  168. [TIP]
  169. ====
  170. See the https://angular.io/guide/http-security-xsrf-protection[Cross-Site Request Forgery (XSRF) protection] guide and the https://angular.io/api/common/http/HttpClientXsrfModule[HttpClientXsrfModule] for more recent information on this topic.
  171. ====
  172. You can configure the `CookieCsrfTokenRepository` using the following configuration:
  173. [[csrf-token-repository-cookie-configuration]]
  174. .Configure `CookieCsrfTokenRepository`
  175. [tabs]
  176. ======
  177. Java::
  178. +
  179. [source,java,role="primary"]
  180. ----
  181. @Configuration
  182. @EnableWebSecurity
  183. public class SecurityConfig {
  184. @Bean
  185. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  186. http
  187. // ...
  188. .csrf((csrf) -> csrf
  189. .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
  190. );
  191. return http.build();
  192. }
  193. }
  194. ----
  195. Kotlin::
  196. +
  197. [source,kotlin,role="secondary"]
  198. ----
  199. import org.springframework.security.config.annotation.web.invoke
  200. @Configuration
  201. @EnableWebSecurity
  202. class SecurityConfig {
  203. @Bean
  204. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  205. http {
  206. // ...
  207. csrf {
  208. csrfTokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
  209. }
  210. }
  211. return http.build()
  212. }
  213. }
  214. ----
  215. XML::
  216. +
  217. [source,xml,role="secondary"]
  218. ----
  219. <http>
  220. <!-- ... -->
  221. <csrf token-repository-ref="tokenRepository"/>
  222. </http>
  223. <b:bean id="tokenRepository"
  224. class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
  225. p:cookieHttpOnly="false"/>
  226. ----
  227. ======
  228. [NOTE]
  229. ====
  230. The example explicitly sets `HttpOnly` to `false`.
  231. This is necessary to let JavaScript frameworks (such as Angular) read it.
  232. If you do not need the ability to read the cookie with JavaScript directly, we _recommend_ omitting `HttpOnly` (by using `new CookieCsrfTokenRepository()` instead) to improve security.
  233. ====
  234. [[csrf-token-repository-custom]]
  235. === Customizing the `CsrfTokenRepository`
  236. There can be cases where you want to implement a custom javadoc:org.springframework.security.web.csrf.CsrfTokenRepository[].
  237. Once you've implemented the `CsrfTokenRepository` interface, you can configure Spring Security to use it with the following configuration:
  238. [[csrf-token-repository-custom-configuration]]
  239. .Configure Custom `CsrfTokenRepository`
  240. [tabs]
  241. ======
  242. Java::
  243. +
  244. [source,java,role="primary"]
  245. ----
  246. @Configuration
  247. @EnableWebSecurity
  248. public class SecurityConfig {
  249. @Bean
  250. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  251. http
  252. // ...
  253. .csrf((csrf) -> csrf
  254. .csrfTokenRepository(new CustomCsrfTokenRepository())
  255. );
  256. return http.build();
  257. }
  258. }
  259. ----
  260. Kotlin::
  261. +
  262. [source,kotlin,role="secondary"]
  263. ----
  264. import org.springframework.security.config.annotation.web.invoke
  265. @Configuration
  266. @EnableWebSecurity
  267. class SecurityConfig {
  268. @Bean
  269. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  270. http {
  271. // ...
  272. csrf {
  273. csrfTokenRepository = CustomCsrfTokenRepository()
  274. }
  275. }
  276. return http.build()
  277. }
  278. }
  279. ----
  280. XML::
  281. +
  282. [source,xml,role="secondary"]
  283. ----
  284. <http>
  285. <!-- ... -->
  286. <csrf token-repository-ref="tokenRepository"/>
  287. </http>
  288. <b:bean id="tokenRepository"
  289. class="example.CustomCsrfTokenRepository"/>
  290. ----
  291. ======
  292. [[csrf-token-request-handler]]
  293. == Handling the `CsrfToken`
  294. The `CsrfToken` is made available to an application using a `CsrfTokenRequestHandler`.
  295. This component is also responsible for resolving the `CsrfToken` from HTTP headers or request parameters.
  296. By default, the <<csrf-token-request-handler-breach,`XorCsrfTokenRequestAttributeHandler`>> is used for providing https://en.wikipedia.org/wiki/BREACH[BREACH] protection of the `CsrfToken`.
  297. Spring Security also provides the <<csrf-token-request-handler-plain,`CsrfTokenRequestAttributeHandler`>> for opting out of BREACH protection.
  298. You can also specify <<csrf-token-request-handler-custom,your own implementation>> to customize the strategy for handling and resolving tokens.
  299. [[csrf-token-request-handler-breach]]
  300. === Using the `XorCsrfTokenRequestAttributeHandler` (BREACH)
  301. The `XorCsrfTokenRequestAttributeHandler` makes the `CsrfToken` available as an `HttpServletRequest` attribute called `_csrf`, and additionally provides protection for https://en.wikipedia.org/wiki/BREACH[BREACH].
  302. [NOTE]
  303. ====
  304. The `CsrfToken` is also made available as a request attribute using the name `CsrfToken.class.getName()`.
  305. This name is not configurable, but the name `_csrf` can be changed using `XorCsrfTokenRequestAttributeHandler#setCsrfRequestAttributeName`.
  306. ====
  307. This implementation also resolves the token value from the request as either a request header (one of <<csrf-token-repository-httpsession,`X-CSRF-TOKEN`>> or <<csrf-token-repository-cookie,`X-XSRF-TOKEN`>> by default) or a request parameter (`_csrf` by default).
  308. [NOTE]
  309. ====
  310. BREACH protection is provided by encoding randomness into the CSRF token value to ensure the returned `CsrfToken` changes on every request.
  311. When the token is later resolved as a header value or request parameter, it is decoded to obtain the raw token which is then compared to the <<csrf-token-repository,persisted `CsrfToken`>>.
  312. ====
  313. Spring Security protects the CSRF token from a BREACH attack by default, so no additional code is necessary.
  314. You can specify the default configuration explicitly using the following configuration:
  315. [[csrf-token-request-handler-breach-configuration]]
  316. .Configure BREACH protection
  317. [tabs]
  318. ======
  319. Java::
  320. +
  321. [source,java,role="primary"]
  322. ----
  323. @Configuration
  324. @EnableWebSecurity
  325. public class SecurityConfig {
  326. @Bean
  327. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  328. http
  329. // ...
  330. .csrf((csrf) -> csrf
  331. .csrfTokenRequestHandler(new XorCsrfTokenRequestAttributeHandler())
  332. );
  333. return http.build();
  334. }
  335. }
  336. ----
  337. Kotlin::
  338. +
  339. [source,kotlin,role="secondary"]
  340. ----
  341. import org.springframework.security.config.annotation.web.invoke
  342. @Configuration
  343. @EnableWebSecurity
  344. class SecurityConfig {
  345. @Bean
  346. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  347. http {
  348. // ...
  349. csrf {
  350. csrfTokenRequestHandler = XorCsrfTokenRequestAttributeHandler()
  351. }
  352. }
  353. return http.build()
  354. }
  355. }
  356. ----
  357. XML::
  358. +
  359. [source,xml,role="secondary"]
  360. ----
  361. <http>
  362. <!-- ... -->
  363. <csrf request-handler-ref="requestHandler"/>
  364. </http>
  365. <b:bean id="requestHandler"
  366. class="org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler"/>
  367. ----
  368. ======
  369. [[csrf-token-request-handler-plain]]
  370. === Using the `CsrfTokenRequestAttributeHandler`
  371. The `CsrfTokenRequestAttributeHandler` makes the `CsrfToken` available as an `HttpServletRequest` attribute called `_csrf`.
  372. [NOTE]
  373. ====
  374. The `CsrfToken` is also made available as a request attribute using the name `CsrfToken.class.getName()`.
  375. This name is not configurable, but the name `_csrf` can be changed using `CsrfTokenRequestAttributeHandler#setCsrfRequestAttributeName`.
  376. ====
  377. This implementation also resolves the token value from the request as either a request header (one of <<csrf-token-repository-httpsession,`X-CSRF-TOKEN`>> or <<csrf-token-repository-cookie,`X-XSRF-TOKEN`>> by default) or a request parameter (`_csrf` by default).
  378. [[csrf-token-request-handler-opt-out-of-breach]]
  379. The primary use of `CsrfTokenRequestAttributeHandler` is to opt-out of BREACH protection of the `CsrfToken`, which can be configured using the following configuration:
  380. .Opt-out of BREACH protection
  381. [tabs]
  382. ======
  383. Java::
  384. +
  385. [source,java,role="primary"]
  386. ----
  387. @Configuration
  388. @EnableWebSecurity
  389. public class SecurityConfig {
  390. @Bean
  391. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  392. http
  393. // ...
  394. .csrf((csrf) -> csrf
  395. .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
  396. );
  397. return http.build();
  398. }
  399. }
  400. ----
  401. Kotlin::
  402. +
  403. [source,kotlin,role="secondary"]
  404. ----
  405. import org.springframework.security.config.annotation.web.invoke
  406. @Configuration
  407. @EnableWebSecurity
  408. class SecurityConfig {
  409. @Bean
  410. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  411. http {
  412. // ...
  413. csrf {
  414. csrfTokenRequestHandler = CsrfTokenRequestAttributeHandler()
  415. }
  416. }
  417. return http.build()
  418. }
  419. }
  420. ----
  421. XML::
  422. +
  423. [source,xml,role="secondary"]
  424. ----
  425. <http>
  426. <!-- ... -->
  427. <csrf request-handler-ref="requestHandler"/>
  428. </http>
  429. <b:bean id="requestHandler"
  430. class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler"/>
  431. ----
  432. ======
  433. [[csrf-token-request-handler-custom]]
  434. === Customizing the `CsrfTokenRequestHandler`
  435. You can implement the `CsrfTokenRequestHandler` interface to customize the strategy for handling and resolving tokens.
  436. [TIP]
  437. ====
  438. The `CsrfTokenRequestHandler` interface is a `@FunctionalInterface` that can be implemented using a lambda expression to customize request handling.
  439. You will need to implement the full interface to customize how tokens are resolved from the request.
  440. See <<csrf-integration-javascript-spa-configuration>> for an example that uses delegation to implement a custom strategy for handling and resolving tokens.
  441. ====
  442. Once you've implemented the `CsrfTokenRequestHandler` interface, you can configure Spring Security to use it with the following configuration:
  443. [[csrf-token-request-handler-custom-configuration]]
  444. .Configure Custom `CsrfTokenRequestHandler`
  445. [tabs]
  446. ======
  447. Java::
  448. +
  449. [source,java,role="primary"]
  450. ----
  451. @Configuration
  452. @EnableWebSecurity
  453. public class SecurityConfig {
  454. @Bean
  455. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  456. http
  457. // ...
  458. .csrf((csrf) -> csrf
  459. .csrfTokenRequestHandler(new CustomCsrfTokenRequestHandler())
  460. );
  461. return http.build();
  462. }
  463. }
  464. ----
  465. Kotlin::
  466. +
  467. [source,kotlin,role="secondary"]
  468. ----
  469. import org.springframework.security.config.annotation.web.invoke
  470. @Configuration
  471. @EnableWebSecurity
  472. class SecurityConfig {
  473. @Bean
  474. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  475. http {
  476. // ...
  477. csrf {
  478. csrfTokenRequestHandler = CustomCsrfTokenRequestHandler()
  479. }
  480. }
  481. return http.build()
  482. }
  483. }
  484. ----
  485. XML::
  486. +
  487. [source,xml,role="secondary"]
  488. ----
  489. <http>
  490. <!-- ... -->
  491. <csrf request-handler-ref="requestHandler"/>
  492. </http>
  493. <b:bean id="requestHandler"
  494. class="example.CustomCsrfTokenRequestHandler"/>
  495. ----
  496. ======
  497. [[deferred-csrf-token]]
  498. == Deferred Loading of the `CsrfToken`
  499. By default, Spring Security defers loading of the `CsrfToken` until it is needed.
  500. [NOTE]
  501. ====
  502. The `CsrfToken` is needed whenever a request is made with an xref:features/exploits/csrf.adoc#csrf-protection-read-only[unsafe HTTP method], such as a POST.
  503. Additionally, it is needed by any request that renders the token to the response, such as a web page with a `<form>` tag that includes a hidden `<input>` for the CSRF token.
  504. ====
  505. Because Spring Security also stores the `CsrfToken` in the `HttpSession` by default, deferred CSRF tokens can improve performance by not requiring the session to be loaded on every request.
  506. [[deferred-csrf-token-opt-out]]
  507. In the event that you want to opt-out of deferred tokens and cause the `CsrfToken` to be loaded on every request, you can do so with the following configuration:
  508. [[deferred-csrf-token-opt-out-configuration]]
  509. .Opt-out of Deferred CSRF Tokens
  510. [tabs]
  511. ======
  512. Java::
  513. +
  514. [source,java,role="primary"]
  515. ----
  516. @Configuration
  517. @EnableWebSecurity
  518. public class SecurityConfig {
  519. @Bean
  520. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  521. XorCsrfTokenRequestAttributeHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();
  522. // set the name of the attribute the CsrfToken will be populated on
  523. requestHandler.setCsrfRequestAttributeName(null);
  524. http
  525. // ...
  526. .csrf((csrf) -> csrf
  527. .csrfTokenRequestHandler(requestHandler)
  528. );
  529. return http.build();
  530. }
  531. }
  532. ----
  533. Kotlin::
  534. +
  535. [source,kotlin,role="secondary"]
  536. ----
  537. import org.springframework.security.config.annotation.web.invoke
  538. @Configuration
  539. @EnableWebSecurity
  540. class SecurityConfig {
  541. @Bean
  542. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  543. val requestHandler = XorCsrfTokenRequestAttributeHandler()
  544. // set the name of the attribute the CsrfToken will be populated on
  545. requestHandler.setCsrfRequestAttributeName(null)
  546. http {
  547. // ...
  548. csrf {
  549. csrfTokenRequestHandler = requestHandler
  550. }
  551. }
  552. return http.build()
  553. }
  554. }
  555. ----
  556. XML::
  557. +
  558. [source,xml,role="secondary"]
  559. ----
  560. <http>
  561. <!-- ... -->
  562. <csrf request-handler-ref="requestHandler"/>
  563. </http>
  564. <b:bean id="requestHandler"
  565. class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler">
  566. <b:property name="csrfRequestAttributeName">
  567. <b:null/>
  568. </b:property>
  569. </b:bean>
  570. ----
  571. ======
  572. [NOTE]
  573. ====
  574. By setting the `csrfRequestAttributeName` to `null`, the `CsrfToken` must first be loaded to determine what attribute name to use.
  575. This causes the `CsrfToken` to be loaded on every request.
  576. ====
  577. [[csrf-integration]]
  578. == Integrating with CSRF Protection
  579. For the xref:features/exploits/csrf.adoc#csrf-protection-stp[synchronizer token pattern] to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request.
  580. This must be included in a part of the request (a form parameter, an HTTP header, or other part) that is not automatically included in the HTTP request by the browser.
  581. The following sections describe the various ways a frontend or client application can integrate with a CSRF-protected backend application:
  582. * <<csrf-integration-form>>
  583. * <<csrf-integration-javascript>>
  584. * <<csrf-integration-mobile>>
  585. [[csrf-integration-form]]
  586. === HTML Forms
  587. To submit an HTML form, the CSRF token must be included in the form as a hidden input.
  588. For example, the rendered HTML might look like:
  589. .CSRF Token in HTML Form
  590. [source,html]
  591. ----
  592. <input type="hidden"
  593. name="_csrf"
  594. value="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>
  595. ----
  596. The following view technologies automatically include the actual CSRF token in a form that has an unsafe HTTP method, such as a POST:
  597. * https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib[Spring’s form tag library]
  598. * https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integration-with-requestdatavalueprocessor[Thymeleaf]
  599. * Any other view technology that integrates with {spring-framework-api-url}org/springframework/web/servlet/support/RequestDataValueProcessor.html[`RequestDataValueProcessor`] (via javadoc:org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor[])
  600. * You can also include the token yourself via the xref:servlet/integrations/jsp-taglibs.adoc#taglibs-csrfinput[csrfInput] tag
  601. If these options are not available, you can take advantage of the fact that the `CsrfToken` is exposed as an <<csrf-token-request-handler,`HttpServletRequest` attribute named `_csrf`>>.
  602. The following example does this with a JSP:
  603. .CSRF Token in HTML Form with Request Attribute
  604. [source,xml]
  605. ----
  606. <c:url var="logoutUrl" value="/logout"/>
  607. <form action="${logoutUrl}"
  608. method="post">
  609. <input type="submit"
  610. value="Log out" />
  611. <input type="hidden"
  612. name="${_csrf.parameterName}"
  613. value="${_csrf.token}"/>
  614. </form>
  615. ----
  616. [[csrf-integration-javascript]]
  617. === JavaScript Applications
  618. JavaScript applications typically use JSON instead of HTML.
  619. If you use JSON, you can submit the CSRF token within an HTTP request header instead of a request parameter.
  620. In order to obtain the CSRF token, you can configure Spring Security to store the expected CSRF token <<csrf-token-repository-cookie,in a cookie>>.
  621. By storing the expected token in a cookie, JavaScript frameworks such as https://angular.io/api/common/http/HttpClientXsrfModule[Angular] can automatically include the actual CSRF token as an HTTP request header.
  622. [TIP]
  623. ====
  624. There are special considerations for BREACH protection and deferred tokens when integrating a single-page application (SPA) with Spring Security's CSRF protection.
  625. A full configuration example is provided in the <<csrf-integration-javascript-spa,next section>>.
  626. ====
  627. You can read about different types of JavaScript applications in the following sections:
  628. * <<csrf-integration-javascript-spa>>
  629. * <<csrf-integration-javascript-mpa>>
  630. * <<csrf-integration-javascript-other>>
  631. [[csrf-integration-javascript-spa]]
  632. ==== Single-Page Applications
  633. There are special considerations for integrating a single-page application (SPA) with Spring Security's CSRF protection.
  634. Recall that Spring Security provides <<csrf-token-request-handler-breach,BREACH protection of the `CsrfToken`>> by default.
  635. When storing the expected CSRF token <<csrf-token-repository-cookie,in a cookie>>, JavaScript applications will only have access to the plain token value and _will not_ have access to the encoded value.
  636. A <<csrf-token-request-handler-custom,customized request handler>> for resolving the actual token value will need to be provided.
  637. In addition, the cookie storing the CSRF token will be cleared upon authentication success and logout success.
  638. Spring Security defers loading a new CSRF token by default, and additional work is required to return a fresh cookie.
  639. [NOTE]
  640. ====
  641. Refreshing the token after authentication success and logout success is required because the javadoc:org.springframework.security.web.csrf.CsrfAuthenticationStrategy[] and javadoc:org.springframework.security.web.csrf.CsrfLogoutHandler[] will clear the previous token.
  642. The client application will not be able to perform an unsafe HTTP request, such as a POST, without obtaining a fresh token.
  643. ====
  644. In order to easily integrate a single-page application with Spring Security, the following configuration can be used:
  645. [[csrf-integration-javascript-spa-configuration]]
  646. .Configure CSRF for Single-Page Application
  647. [tabs]
  648. ======
  649. Java::
  650. +
  651. [source,java,role="primary"]
  652. ----
  653. @Configuration
  654. @EnableWebSecurity
  655. public class SecurityConfig {
  656. @Bean
  657. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  658. http
  659. // ...
  660. .csrf((csrf) -> csrf.spa());
  661. return http.build();
  662. }
  663. }
  664. ----
  665. Kotlin::
  666. +
  667. [source,kotlin,role="secondary"]
  668. ----
  669. import org.springframework.security.config.annotation.web.invoke
  670. @Configuration
  671. @EnableWebSecurity
  672. class SecurityConfig {
  673. @Bean
  674. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  675. http {
  676. // ...
  677. csrf {
  678. spa()
  679. }
  680. }
  681. return http.build()
  682. }
  683. }
  684. ----
  685. XML::
  686. +
  687. [source,xml,role="secondary"]
  688. ----
  689. <http>
  690. <!-- ... -->
  691. <csrf>
  692. <spa />
  693. </csrf>
  694. </http>
  695. ----
  696. ======
  697. [[csrf-integration-javascript-mpa]]
  698. ==== Multi-Page Applications
  699. For multi-page applications where JavaScript is loaded on each page, an alternative to exposing the CSRF token <<csrf-token-repository-cookie,in a cookie>> is to include the CSRF token within your `meta` tags.
  700. The HTML might look something like this:
  701. .CSRF Token in HTML Meta Tag
  702. [source,html]
  703. ----
  704. <html>
  705. <head>
  706. <meta name="_csrf" content="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>
  707. <meta name="_csrf_header" content="X-CSRF-TOKEN"/>
  708. <!-- ... -->
  709. </head>
  710. <!-- ... -->
  711. </html>
  712. ----
  713. In order to include the CSRF token in the request, you can take advantage of the fact that the `CsrfToken` is exposed as an <<csrf-token-request-handler,`HttpServletRequest` attribute named `_csrf`>>.
  714. The following example does this with a JSP:
  715. .CSRF Token in HTML Meta Tag with Request Attribute
  716. [source,html]
  717. ----
  718. <html>
  719. <head>
  720. <meta name="_csrf" content="${_csrf.token}"/>
  721. <!-- default header name is X-CSRF-TOKEN -->
  722. <meta name="_csrf_header" content="${_csrf.headerName}"/>
  723. <!-- ... -->
  724. </head>
  725. <!-- ... -->
  726. </html>
  727. ----
  728. Once the meta tags contain the CSRF token, the JavaScript code can read the meta tags and include the CSRF token as a header.
  729. If you use jQuery, you can do this with the following code:
  730. .Include CSRF Token in AJAX Request
  731. [source,javascript]
  732. ----
  733. $(function () {
  734. var token = $("meta[name='_csrf']").attr("content");
  735. var header = $("meta[name='_csrf_header']").attr("content");
  736. $(document).ajaxSend(function(e, xhr, options) {
  737. xhr.setRequestHeader(header, token);
  738. });
  739. });
  740. ----
  741. [[csrf-integration-javascript-other]]
  742. ==== Other JavaScript Applications
  743. Another option for JavaScript applications is to include the CSRF token in an HTTP response header.
  744. One way to achieve this is through the use of a `@ControllerAdvice` with the xref:servlet/integrations/mvc.adoc#mvc-csrf-resolver[`CsrfTokenArgumentResolver`].
  745. The following is an example of `@ControllerAdvice` that applies to all controller endpoints in the application:
  746. [[controller-advice]]
  747. .CSRF Token in HTTP Response Header
  748. [tabs]
  749. ======
  750. Java::
  751. +
  752. [source,java,role="primary"]
  753. ----
  754. @ControllerAdvice
  755. public class CsrfControllerAdvice {
  756. @ModelAttribute
  757. public void getCsrfToken(HttpServletResponse response, CsrfToken csrfToken) {
  758. response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken());
  759. }
  760. }
  761. ----
  762. Kotlin::
  763. +
  764. [source,kotlin,role="secondary"]
  765. ----
  766. @ControllerAdvice
  767. class CsrfControllerAdvice {
  768. @ModelAttribute
  769. fun getCsrfToken(response: HttpServletResponse, csrfToken: CsrfToken) {
  770. response.setHeader(csrfToken.headerName, csrfToken.token)
  771. }
  772. }
  773. ----
  774. ======
  775. [NOTE]
  776. ====
  777. Because this `@ControllerAdvice` applies to all endpoints in the application, it will cause the CSRF token to be loaded on every request, which can negate the benefits of <<deferred-csrf-token,deferred tokens>> when using the <<csrf-token-repository-httpsession,`HttpSessionCsrfTokenRepository`>>.
  778. However, this is not usually an issue when using the <<csrf-token-repository-cookie,`CookieCsrfTokenRepository`>>.
  779. ====
  780. [NOTE]
  781. ====
  782. It is important to remember that controller endpoints and controller advice are called _after_ the Spring Security filter chain.
  783. This means that this `@ControllerAdvice` will only be applied if the request passes through the filter chain to your application.
  784. See the configuration for <<csrf-integration-javascript-spa-configuration,single-page applications>> for an example of adding a filter to the filter chain for earlier access to the `HttpServletResponse`.
  785. ====
  786. The CSRF token will now be available in a response header (<<csrf-token-repository-httpsession,`X-CSRF-TOKEN`>> or <<csrf-token-repository-cookie,`X-XSRF-TOKEN`>> by default) for any custom endpoints the controller advice applies to.
  787. Any request to the backend can be used to obtain the token from the response, and a subsequent request can include the token in a request header with the same name.
  788. [[csrf-integration-mobile]]
  789. === Mobile Applications
  790. Like <<csrf-integration-javascript,JavaScript applications>>, mobile applications typically use JSON instead of HTML.
  791. A backend application that _does not_ serve browser traffic may choose to <<disable-csrf,disable CSRF>>.
  792. In that case, no additional work is required.
  793. However, a backend application that also serves browser traffic and therefore _still requires_ CSRF protection may continue to store the `CsrfToken` <<csrf-token-repository-httpsession,in the session>> instead of <<csrf-token-repository-cookie,in a cookie>>.
  794. In this case, a typical pattern for integrating with the backend is to expose a `/csrf` endpoint to allow the frontend (mobile or browser client) to request a CSRF token on demand.
  795. The benefit of using this pattern is that the CSRF token <<deferred-csrf-token,can continue to be deferred>> and only needs to be loaded from the session when a request requires CSRF protection.
  796. The use of a custom endpoint also means the client application can request that a new token be generated on demand (if necessary) by issuing an explicit request.
  797. [TIP]
  798. ====
  799. This pattern can be used for any type of application that requires CSRF protection, not just mobile applications.
  800. While this approach isn't typically required in those cases, it is another option for integrating with a CSRF-protected backend.
  801. ====
  802. The following is an example of the `/csrf` endpoint that makes use of the xref:servlet/integrations/mvc.adoc#mvc-csrf-resolver[`CsrfTokenArgumentResolver`]:
  803. [[csrf-endpoint]]
  804. .The `/csrf` endpoint
  805. [tabs]
  806. ======
  807. Java::
  808. +
  809. [source,java,role="primary"]
  810. ----
  811. @RestController
  812. public class CsrfController {
  813. @GetMapping("/csrf")
  814. public CsrfToken csrf(CsrfToken csrfToken) {
  815. return csrfToken;
  816. }
  817. }
  818. ----
  819. Kotlin::
  820. +
  821. [source,kotlin,role="secondary"]
  822. ----
  823. @RestController
  824. class CsrfController {
  825. @GetMapping("/csrf")
  826. fun csrf(csrfToken: CsrfToken): CsrfToken {
  827. return csrfToken
  828. }
  829. }
  830. ----
  831. ======
  832. [NOTE]
  833. ====
  834. You may consider adding `.requestMatchers("/csrf").permitAll()` if the endpoint above is required prior to authenticating with the server.
  835. ====
  836. This endpoint should be called to obtain a CSRF token when the application is launched or initialized (e.g. at load time), and also after authentication success and logout success.
  837. [NOTE]
  838. ====
  839. Refreshing the token after authentication success and logout success is required because the javadoc:org.springframework.security.web.csrf.CsrfAuthenticationStrategy[] and javadoc:org.springframework.security.web.csrf.CsrfLogoutHandler[] will clear the previous token.
  840. The client application will not be able to perform an unsafe HTTP request, such as a POST, without obtaining a fresh token.
  841. ====
  842. Once you've obtained the CSRF token, you will need to include it as an HTTP request header (one of <<csrf-token-repository-httpsession,`X-CSRF-TOKEN`>> or <<csrf-token-repository-cookie,`X-XSRF-TOKEN`>> by default) yourself.
  843. [[csrf-access-denied-handler]]
  844. == Handle `AccessDeniedException`
  845. To handle an `AccessDeniedException` such as `InvalidCsrfTokenException`, you can configure Spring Security to handle these exceptions in any way you like.
  846. For example, you can configure a custom access denied page using the following configuration:
  847. [[csrf-access-denied-handler-configuration]]
  848. .Configure `AccessDeniedHandler`
  849. [tabs]
  850. ======
  851. Java::
  852. +
  853. [source,java,role="primary"]
  854. ----
  855. @Configuration
  856. @EnableWebSecurity
  857. public class SecurityConfig {
  858. @Bean
  859. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  860. http
  861. // ...
  862. .exceptionHandling((exceptionHandling) -> exceptionHandling
  863. .accessDeniedPage("/access-denied")
  864. );
  865. return http.build();
  866. }
  867. }
  868. ----
  869. Kotlin::
  870. +
  871. [source,kotlin,role="secondary"]
  872. ----
  873. import org.springframework.security.config.annotation.web.invoke
  874. @Configuration
  875. @EnableWebSecurity
  876. class SecurityConfig {
  877. @Bean
  878. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  879. http {
  880. // ...
  881. exceptionHandling {
  882. accessDeniedPage = "/access-denied"
  883. }
  884. }
  885. return http.build()
  886. }
  887. }
  888. ----
  889. XML::
  890. +
  891. [source,xml,role="secondary"]
  892. ----
  893. <http>
  894. <!-- ... -->
  895. <access-denied-handler error-page="/access-denied"/>
  896. </http>
  897. ----
  898. ======
  899. [[csrf-testing]]
  900. == CSRF Testing
  901. You can use Spring Security's xref:servlet/test/mockmvc/setup.adoc[testing support] and xref:servlet/test/mockmvc/csrf.adoc[`CsrfRequestPostProcessor`] to test CSRF protection, like this:
  902. [[csrf-testing-example]]
  903. .Test CSRF Protection
  904. [tabs]
  905. ======
  906. Java::
  907. +
  908. [source,java,role="primary"]
  909. ----
  910. import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
  911. import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
  912. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
  913. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
  914. @ExtendWith(SpringExtension.class)
  915. @ContextConfiguration(classes = SecurityConfig.class)
  916. @WebAppConfiguration
  917. public class CsrfTests {
  918. private MockMvc mockMvc;
  919. @BeforeEach
  920. public void setUp(WebApplicationContext applicationContext) {
  921. this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext)
  922. .apply(springSecurity())
  923. .build();
  924. }
  925. @Test
  926. public void loginWhenValidCsrfTokenThenSuccess() throws Exception {
  927. this.mockMvc.perform(post("/login").with(csrf())
  928. .accept(MediaType.TEXT_HTML)
  929. .param("username", "user")
  930. .param("password", "password"))
  931. .andExpect(status().is3xxRedirection())
  932. .andExpect(header().string(HttpHeaders.LOCATION, "/"));
  933. }
  934. @Test
  935. public void loginWhenInvalidCsrfTokenThenForbidden() throws Exception {
  936. this.mockMvc.perform(post("/login").with(csrf().useInvalidToken())
  937. .accept(MediaType.TEXT_HTML)
  938. .param("username", "user")
  939. .param("password", "password"))
  940. .andExpect(status().isForbidden());
  941. }
  942. @Test
  943. public void loginWhenMissingCsrfTokenThenForbidden() throws Exception {
  944. this.mockMvc.perform(post("/login")
  945. .accept(MediaType.TEXT_HTML)
  946. .param("username", "user")
  947. .param("password", "password"))
  948. .andExpect(status().isForbidden());
  949. }
  950. @Test
  951. @WithMockUser
  952. public void logoutWhenValidCsrfTokenThenSuccess() throws Exception {
  953. this.mockMvc.perform(post("/logout").with(csrf())
  954. .accept(MediaType.TEXT_HTML))
  955. .andExpect(status().is3xxRedirection())
  956. .andExpect(header().string(HttpHeaders.LOCATION, "/login?logout"));
  957. }
  958. }
  959. ----
  960. Kotlin::
  961. +
  962. [source,kotlin,role="secondary"]
  963. ----
  964. import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*
  965. import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*
  966. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*
  967. import org.springframework.test.web.servlet.result.MockMvcResultMatchers.*
  968. @ExtendWith(SpringExtension::class)
  969. @ContextConfiguration(classes = [SecurityConfig::class])
  970. @WebAppConfiguration
  971. class CsrfTests {
  972. private lateinit var mockMvc: MockMvc
  973. @BeforeEach
  974. fun setUp(applicationContext: WebApplicationContext) {
  975. mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext)
  976. .apply<DefaultMockMvcBuilder>(springSecurity())
  977. .build()
  978. }
  979. @Test
  980. fun loginWhenValidCsrfTokenThenSuccess() {
  981. mockMvc.perform(post("/login").with(csrf())
  982. .accept(MediaType.TEXT_HTML)
  983. .param("username", "user")
  984. .param("password", "password"))
  985. .andExpect(status().is3xxRedirection)
  986. .andExpect(header().string(HttpHeaders.LOCATION, "/"))
  987. }
  988. @Test
  989. fun loginWhenInvalidCsrfTokenThenForbidden() {
  990. mockMvc.perform(post("/login").with(csrf().useInvalidToken())
  991. .accept(MediaType.TEXT_HTML)
  992. .param("username", "user")
  993. .param("password", "password"))
  994. .andExpect(status().isForbidden)
  995. }
  996. @Test
  997. fun loginWhenMissingCsrfTokenThenForbidden() {
  998. mockMvc.perform(post("/login")
  999. .accept(MediaType.TEXT_HTML)
  1000. .param("username", "user")
  1001. .param("password", "password"))
  1002. .andExpect(status().isForbidden)
  1003. }
  1004. @Test
  1005. @WithMockUser
  1006. @Throws(Exception::class)
  1007. fun logoutWhenValidCsrfTokenThenSuccess() {
  1008. mockMvc.perform(post("/logout").with(csrf())
  1009. .accept(MediaType.TEXT_HTML))
  1010. .andExpect(status().is3xxRedirection)
  1011. .andExpect(header().string(HttpHeaders.LOCATION, "/login?logout"))
  1012. }
  1013. }
  1014. ----
  1015. ======
  1016. [[disable-csrf]]
  1017. == Disable CSRF Protection
  1018. By default, CSRF protection is enabled, which affects <<csrf-integration,integrating with the backend>> and <<csrf-testing,testing>> your application.
  1019. Before disabling CSRF protection, consider whether it xref:features/exploits/csrf.adoc#csrf-when[makes sense for your application].
  1020. You can also consider whether only certain endpoints do not require CSRF protection and configure an ignoring rule, as in the following example:
  1021. [[disable-csrf-ignoring-configuration]]
  1022. .Ignoring Requests
  1023. [tabs]
  1024. ======
  1025. Java::
  1026. +
  1027. [source,java,role="primary"]
  1028. ----
  1029. @Configuration
  1030. @EnableWebSecurity
  1031. public class SecurityConfig {
  1032. @Bean
  1033. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1034. http
  1035. // ...
  1036. .csrf((csrf) -> csrf
  1037. .ignoringRequestMatchers("/api/*")
  1038. );
  1039. return http.build();
  1040. }
  1041. }
  1042. ----
  1043. Kotlin::
  1044. +
  1045. [source,kotlin,role="secondary"]
  1046. ----
  1047. import org.springframework.security.config.annotation.web.invoke
  1048. @Configuration
  1049. @EnableWebSecurity
  1050. class SecurityConfig {
  1051. @Bean
  1052. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  1053. http {
  1054. // ...
  1055. csrf {
  1056. ignoringRequestMatchers("/api/*")
  1057. }
  1058. }
  1059. return http.build()
  1060. }
  1061. }
  1062. ----
  1063. XML::
  1064. +
  1065. [source,xml,role="secondary"]
  1066. ----
  1067. <http>
  1068. <!-- ... -->
  1069. <csrf request-matcher-ref="csrfMatcher"/>
  1070. </http>
  1071. <b:bean id="csrfMatcher"
  1072. class="org.springframework.security.web.util.matcher.AndRequestMatcher">
  1073. <b:constructor-arg value="#{T(org.springframework.security.web.csrf.CsrfFilter).DEFAULT_CSRF_MATCHER}"/>
  1074. <b:constructor-arg>
  1075. <b:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
  1076. <b:bean class="org.springframework.security.config.http.PathPatternRequestMatcherFactoryBean">
  1077. <b:constructor-arg value="/api/*"/>
  1078. </b:bean>
  1079. </b:bean>
  1080. </b:constructor-arg>
  1081. </b:bean>
  1082. ----
  1083. ======
  1084. If you need to disable CSRF protection, you can do so using the following configuration:
  1085. [[disable-csrf-configuration]]
  1086. .Disable CSRF
  1087. [tabs]
  1088. ======
  1089. Java::
  1090. +
  1091. [source,java,role="primary"]
  1092. ----
  1093. @Configuration
  1094. @EnableWebSecurity
  1095. public class SecurityConfig {
  1096. @Bean
  1097. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1098. http
  1099. // ...
  1100. .csrf((csrf) -> csrf.disable());
  1101. return http.build();
  1102. }
  1103. }
  1104. ----
  1105. Kotlin::
  1106. +
  1107. [source,kotlin,role="secondary"]
  1108. ----
  1109. import org.springframework.security.config.annotation.web.invoke
  1110. @Configuration
  1111. @EnableWebSecurity
  1112. class SecurityConfig {
  1113. @Bean
  1114. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  1115. http {
  1116. // ...
  1117. csrf {
  1118. disable()
  1119. }
  1120. }
  1121. return http.build()
  1122. }
  1123. }
  1124. ----
  1125. XML::
  1126. +
  1127. [source,xml,role="secondary"]
  1128. ----
  1129. <http>
  1130. <!-- ... -->
  1131. <csrf disabled="true"/>
  1132. </http>
  1133. ----
  1134. ======
  1135. [[csrf-considerations]]
  1136. == CSRF Considerations
  1137. There are a few special considerations when implementing protection against CSRF attacks.
  1138. This section discusses those considerations as they pertain to servlet environments.
  1139. See xref:features/exploits/csrf.adoc#csrf-considerations[CSRF Considerations] for a more general discussion.
  1140. [[csrf-considerations-login]]
  1141. === Logging In
  1142. It is important to xref:features/exploits/csrf.adoc#csrf-considerations-login[require CSRF for log in] requests to protect against forging log in attempts.
  1143. Spring Security's servlet support does this out of the box.
  1144. [[csrf-considerations-logout]]
  1145. === Logging Out
  1146. It is important to xref:features/exploits/csrf.adoc#csrf-considerations-logout[require CSRF for log out] requests to protect against forging logout attempts.
  1147. If CSRF protection is enabled (the default), Spring Security's `LogoutFilter` will only process HTTP POST requests.
  1148. This ensures that logging out requires a CSRF token and that a malicious user cannot forcibly log your users out.
  1149. The easiest approach is to use a form to log the user out.
  1150. If you really want a link, you can use JavaScript to have the link perform a POST (maybe on a hidden form).
  1151. For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that performs the POST.
  1152. If you really want to use HTTP GET with logout, you can do so.
  1153. However, remember that this is generally not recommended.
  1154. For example, the following logs out when the `/logout` URL is requested with any HTTP method:
  1155. .Log Out with Any HTTP Method
  1156. [tabs]
  1157. ======
  1158. Java::
  1159. +
  1160. [source,java,role="primary"]
  1161. ----
  1162. @Configuration
  1163. @EnableWebSecurity
  1164. public class SecurityConfig {
  1165. @Bean
  1166. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1167. http
  1168. // ...
  1169. .logout((logout) -> logout
  1170. .logoutRequestMatcher(PathPatternRequestMatcher.withDefaults().matcher("/logout"))
  1171. );
  1172. return http.build();
  1173. }
  1174. }
  1175. ----
  1176. Kotlin::
  1177. +
  1178. [source,kotlin,role="secondary"]
  1179. ----
  1180. import org.springframework.security.config.annotation.web.invoke
  1181. @Configuration
  1182. @EnableWebSecurity
  1183. class SecurityConfig {
  1184. @Bean
  1185. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  1186. http {
  1187. // ...
  1188. logout {
  1189. logoutRequestMatcher = PathPatternRequestMatcher.withDefaults().matcher("/logout")
  1190. }
  1191. }
  1192. return http.build()
  1193. }
  1194. }
  1195. ----
  1196. ======
  1197. See the xref:servlet/authentication/logout.adoc[Logout] chapter for more information.
  1198. [[considerations-csrf-timeouts]]
  1199. === CSRF and Session Timeouts
  1200. By default, Spring Security stores the CSRF token in the `HttpSession` using the <<csrf-token-repository-httpsession,`HttpSessionCsrfTokenRepository`>>.
  1201. This can lead to a situation where the session expires, leaving no CSRF token to validate against.
  1202. We have already discussed xref:features/exploits/csrf.adoc#csrf-considerations-timeouts[general solutions] to session timeouts.
  1203. This section discusses the specifics of CSRF timeouts as it pertains to the servlet support.
  1204. You can change the storage of the CSRF token to be in a cookie.
  1205. For details, see the <<csrf-token-repository-cookie>> section.
  1206. If a token does expire, you might want to customize how it is handled by specifying a <<csrf-access-denied-handler,custom `AccessDeniedHandler`>>.
  1207. The custom `AccessDeniedHandler` can process the `InvalidCsrfTokenException` any way you like.
  1208. [[csrf-considerations-multipart]]
  1209. === Multipart (file upload)
  1210. We have xref:features/exploits/csrf.adoc#csrf-considerations-multipart[already discussed] how protecting multipart requests (file uploads) from CSRF attacks causes a https://en.wikipedia.org/wiki/Chicken_or_the_egg[chicken and the egg] problem.
  1211. When JavaScript is available, we _recommend_ <<csrf-integration-javascript-other,including the CSRF token in an HTTP request header>> to side-step the issue.
  1212. If JavaScript is not available, the following sections discuss options for placing the CSRF token in the <<csrf-considerations-multipart-body,body>> and <<csrf-considerations-multipart-url,url>> within a servlet application.
  1213. [NOTE]
  1214. ====
  1215. You can find more information about using multipart forms with Spring in the https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-multipart[Multipart Resolver] section of the Spring reference and the {spring-framework-api-url}org/springframework/web/multipart/support/MultipartFilter.html[`MultipartFilter` javadoc].
  1216. ====
  1217. [[csrf-considerations-multipart-body]]
  1218. ==== Place CSRF Token in the Body
  1219. We have xref:features/exploits/csrf.adoc#csrf-considerations-multipart-body[already discussed] the tradeoffs of placing the CSRF token in the body.
  1220. In this section, we discuss how to configure Spring Security to read the CSRF from the body.
  1221. To read the CSRF token from the body, the `MultipartFilter` is specified before the Spring Security filter.
  1222. Specifying the `MultipartFilter` before the Spring Security filter means that there is no authorization for invoking the `MultipartFilter`, which means anyone can place temporary files on your server.
  1223. However, only authorized users can submit a file that is processed by your application.
  1224. In general, this is the recommended approach because the temporary file upload should have a negligible impact on most servers.
  1225. .Configure `MultipartFilter`
  1226. [tabs]
  1227. ======
  1228. Java::
  1229. +
  1230. [source,java,role="primary"]
  1231. ----
  1232. public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
  1233. @Override
  1234. protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
  1235. insertFilters(servletContext, new MultipartFilter());
  1236. }
  1237. }
  1238. ----
  1239. Kotlin::
  1240. +
  1241. [source,kotlin,role="secondary"]
  1242. ----
  1243. class SecurityApplicationInitializer : AbstractSecurityWebApplicationInitializer() {
  1244. override fun beforeSpringSecurityFilterChain(servletContext: ServletContext?) {
  1245. insertFilters(servletContext, MultipartFilter())
  1246. }
  1247. }
  1248. ----
  1249. XML::
  1250. +
  1251. [source,xml,role="secondary"]
  1252. ----
  1253. <filter>
  1254. <filter-name>MultipartFilter</filter-name>
  1255. <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
  1256. </filter>
  1257. <filter>
  1258. <filter-name>springSecurityFilterChain</filter-name>
  1259. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  1260. </filter>
  1261. <filter-mapping>
  1262. <filter-name>MultipartFilter</filter-name>
  1263. <url-pattern>/*</url-pattern>
  1264. </filter-mapping>
  1265. <filter-mapping>
  1266. <filter-name>springSecurityFilterChain</filter-name>
  1267. <url-pattern>/*</url-pattern>
  1268. </filter-mapping>
  1269. ----
  1270. ======
  1271. [NOTE]
  1272. ====
  1273. To ensure that `MultipartFilter` is specified before the Spring Security filter with XML configuration, you can ensure the `<filter-mapping>` element of the `MultipartFilter` is placed before the `springSecurityFilterChain` within the `web.xml` file.
  1274. ====
  1275. [[csrf-considerations-multipart-url]]
  1276. ==== Include a CSRF Token in a URL
  1277. If letting unauthorized users upload temporary files is not acceptable, an alternative is to place the `MultipartFilter` after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form.
  1278. Since the `CsrfToken` is exposed as an <<csrf-token-request-handler,`HttpServletRequest` attribute named `_csrf`>>, we can use that to create an `action` with the CSRF token in it.
  1279. The following example does this with a JSP:
  1280. .CSRF Token in Action
  1281. [source,html]
  1282. ----
  1283. <form method="post"
  1284. action="./upload?${_csrf.parameterName}=${_csrf.token}"
  1285. enctype="multipart/form-data">
  1286. ----
  1287. [[csrf-considerations-override-method]]
  1288. === HiddenHttpMethodFilter
  1289. We have xref:features/exploits/csrf.adoc#csrf-considerations-multipart-body[already discussed] the trade-offs of placing the CSRF token in the body.
  1290. In Spring's Servlet support, overriding the HTTP method is done by using {spring-framework-api-url}org/springframework/web/filter/reactive/HiddenHttpMethodFilter.html[`HiddenHttpMethodFilter`].
  1291. You can find more information in the https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-rest-method-conversion[HTTP Method Conversion] section of the reference documentation.
  1292. [[csrf-further-reading]]
  1293. == Further Reading
  1294. Now that you have reviewed CSRF protection, consider learning more about xref:servlet/exploits/index.adoc[exploit protection] including xref:servlet/exploits/headers.adoc[secure headers] and the xref:servlet/exploits/firewall.adoc[HTTP firewall] or move on to learning how to xref:servlet/test/index.adoc[test] your application.