Spring Security — 8) Spring Security CSRF Attack Simulation & CSRF Setup and Customization (Cross-Site Request Forgery)
What is the CSRF(Cross site request forgery) attack
- Cross-site request forgery is a web security vulnerability which an attacker can trick a user into clicking a malicious link that triggers undesirable or unexpected side effects.
- This attack allows an attacker to induce users to perform actions that they do not intend to perform.
- In a successful CSRF attack might change user email/password address on the system.
- Usually GET requests is used by an attacker. Because GET requests are the only type of HTTP request that contains the entire of the request’s contents in a URL.
How Does CSRF attacks work?
Three conditions must match:
- There must be an action such that modifying permission for users (for example, changing password action, email action etc..)
- Action should be performed on cookie based session. For example if one user wants to change his/her password, he/she should send his/her cookie to the server. (otherwise server can not know the correspond user)
- There will be none unpredictable request parameters. For example when user is sending post request, creating & sending random request parameter(this can be done in the server side) can be a problem for attacker.
Let’s say there is post request to change email address of user, like this one:
- Right now, attacker can create a web site like this one:
- If a victim user visits the attacker’s webpage, the following will happen:
- Attacker’s page will trigger HTTP post request to the vulnerable website.
- If user is logged in to the sample.com, user’s browser will automatically include user’s session cookie in the request.
- Then attacker’s webpage will process the request in the normal way, after all attacker will change the user’s email with something else.
CSRF Protection
- To protect from CSRF attacks, do not allow GET request to change the state of the server. Website should use GET requests only to fetch web pages or other resources.
- POST requests may do some sensitive stuff. Only our forms and JavaScript must perform these actions. To do that we use randomized anti-CSRF cookie
Cookies are small pieces of text passed back and forth between the browser and web server in HTTP headers. If the web server returns an HTTP response containing a header value like Set-Cookie: _xsrf=5978e29d4ef434a1 , the browser will send back the same information in the next HTTP request in a header with form Cookie: _xsrf=5978e29d4ef434a1
- Secure websites use anti-CSRF cookies to verify that POST requests originate from pages hosted on the same web domain.
- However using cookies are not the only solution for CSRF attack, because an attacker can steal csrf token and use it for subsequent requests. Therefore we need a solution such as only send the cookie which was initiated by the webserver. Solution for that is SameSite=Strict
- With this instruct, browser will only send the cookies initiated by web-server not third-party
Project Setup
To simulate CSRF attacks, first create a simple spring boot project. This project will contain the following dependencies:
- Spring Web
- Spring Security
- Thymeleaf
And create home controller which returns the homePage.html:
Create homePage.html inside the resources/templates folder:
Run the project, and try to connect localhost:8080 , you will be redirected to the login page, username will be user and password can be found in the console:
After successful login, you will see the homePage.
To logout just go to the http://localhost:8080/logout
Where is the CSRF token
Spring Security will enable the CSRF token by default, if you want to see where csrf token is, after logout inspect the login form and you will see the hidden variable called _csrf :

Create PasswordChange Post Endpoint
First create a post endpoint (just assume that this post endpoint is responsible to change user’s password):
CustomerPasswordService is just a dummy service:
Update the homePage.html (just add the form )
Create the passwordChanged.html :
Run the application and press the button, you will be redirected to the passwordChanged.html and you will see your new password also in the console you will see the following outputs:
Disable CSRF protection
To disable CSRF protection, just override configuration configure(HttpSecurity http)
Disabling the CSRF protection is not recommended
CSRF attack simulation
Make sure that you disabled the CSRF protection
The best way to understand why CSRF protection is needed is to generate attack and to see what’s happening in the background.
Attacker creates a simple html page
Create an simple html file called attacker.html
Let’s assume that I am a influencer and somebody wants to connect me 🙂 (because I have done awesome jobs/works etc.. according to the attacker 🙂 )
Please look at the action, it is the our changePassword endpoint (which of course full url) and also attacker will try to set the legitimate customer’s password something else.
Simulate Attack
ow, when you are logged-in the application, please open the attacker.html page in the browser chrome/firefox etc.. then click the button See Contact Information
After clicking the button, you will be redirected to the page http://localhost:8080/changePassword with this output:
You can verify that in the console as well:
That’s the CSRF attack, attacker triggers the user to perform an action on behalf of the user
Now, let’s see how spring security protect our customer(s).
Protect page with random csrf token
Enable the csrf protection via comment out this line:
and re-run the project:
When we enable csrf protection:
- Spring boot will generate random token (hard to guess for attacker)
- When performing mutation actions (such as post, put, delete requests), spring security will look for the token, if token was not found, spring security will reject the request)
After successful login, try to change your password in the homePage. You will get the Whitelabel Error Page response, after submitting the form:
You can also verify that in the console (There will be no outputs)
How Did I Pass the Login Form?
You may ask “if I can not pass the password change form, how did i pass the login form?” answer is: Spring will automatically add the csrf token in the request (take look at the picture in the section Where is the CSRF token ?)
Let’s protect the password form.
Protect change password form
With thymeleaf engine, it is easy: (update the homePage.html )
Run the project. In the password form, inspect the elements:

Now, we have the csrf token, customer can change his/her password
Now, try to change customer password with attacker email
Simulate attack with CSRF protection
Just run the attack email in browser (when you are logged-in) and click the link. You will get the Whitelabel error page, because there is not csrf token then Spring security will reject the request.
How Random Token Generated
- Just look at the HttpSessionCsrfTokenRepository , you will see this method:
Where to store CSRF token
By default csrf token stored in the HttpSession and validated by server-side. In spring security HttpSessionCsrfTokenRepository is responsible for that.
How to debug CSRF operations
Just add the debug point to the CsrfFilter.doFilterInternal(. ) method
How to customize CSRF token
You can customize with CsrfConfigurer<HttpSecurity>
How to disable CSRF protection for specific endpoint(s)
Here is the example configuration for that, you can use it for your project:
How to customize CSRF repository algorithm
Spring Security will provide an interface called interface CsrfTokenRepository to customize everything related to CSRF.
CsrfToken is the another interface to provide information about CSRF token in the spring application:
You can implement your own repository.
Do not customize the csrf repository unless you know what you are doing. Custom implementation can cause security vulnerabilities !!
You can find the example in my github repo , especially: MyCsrfRepository
Cross Site Request Forgery (CSRF)
Spring provides comprehensive support for protecting against Cross Site Request Forgery (CSRF) attacks. In the following sections, we explore:
This portion of the documentation discusses the general topic of CSRF protection. See the relevant sections for specific information on CSRF protection for servlet and WebFlux based applications.
What is a CSRF Attack?
The best way to understand a CSRF attack is by taking a look at a concrete example.
Assume that your bank’s website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the transfer form might look like:
The corresponding HTTP request might look like:
Now pretend you authenticate to your bank’s website and then, without logging out, visit an evil website. The evil website contains an HTML page with the following form:
You like to win money, so you click on the submit button. In the process, you have unintentionally transferred $100 to a malicious user. This happens because, while the evil website cannot see your cookies, the cookies associated with your bank are still sent along with the request.
Worse yet, this whole process could have been automated by using JavaScript. This means you did not even need to click on the button. Furthermore, it could just as easily happen when visiting an honest site that is a victim of a XSS attack. So how do we protect our users from such attacks?
Protecting Against CSRF Attacks
The reason that a CSRF attack is possible is that the HTTP request from the victim’s website and the request from the attacker’s website are exactly the same. This means there is no way to reject requests coming from the evil website and allow only requests coming from the bank’s website. To protect against CSRF attacks, we need to ensure there is something in the request that the evil site is unable to provide so we can differentiate the two requests.
Spring provides two mechanisms to protect against CSRF attacks:
Specifying the SameSite Attribute on your session cookie
Both protections require that Safe Methods be Idempotent.
Safe Methods Must be Idempotent
For either protection against CSRF to work, the application must ensure that «safe» HTTP methods are idempotent. This means that requests with the HTTP GET , HEAD , OPTIONS , and TRACE methods should not change the state of the application.
Synchronizer Token Pattern
The predominant and most comprehensive way to protect against CSRF attacks is to use the Synchronizer Token Pattern. This solution is to ensure that each HTTP request requires, in addition to our session cookie, a secure random generated value called a CSRF token be present in the HTTP request.
When an HTTP request is submitted, the server must look up the expected CSRF token and compare it against the actual CSRF token in the HTTP request. If the values do not match, the HTTP request should be rejected.
The key to this working is that the actual CSRF token should be in a part of the HTTP request that is not automatically included by the browser. For example, requiring the actual CSRF token in an HTTP parameter or an HTTP header will protect against CSRF attacks. Requiring the actual CSRF token in a cookie does not work because cookies are automatically included in the HTTP request by the browser.
We can relax the expectations to require only the actual CSRF token for each HTTP request that updates the state of the application. For that to work, our application must ensure that safe HTTP methods are idempotent. This improves usability, since we want to allow linking to our website from external sites. Additionally, we do not want to include the random token in HTTP GET, as this can cause the tokens to be leaked.
Consider how our example would change when we use the Synchronizer Token Pattern. Assume that the actual CSRF token is required to be in an HTTP parameter named _csrf . Our application’s transfer form would look like:
The form now contains a hidden input with the value of the CSRF token. External sites cannot read the CSRF token since the same origin policy ensures the evil site cannot read the response.
The corresponding HTTP request to transfer money would look like this:
You will notice that the HTTP request now contains the _csrf parameter with a secure random value. The evil website will not be able to provide the correct value for the _csrf parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual CSRF token to the expected CSRF token.
SameSite Attribute
An emerging way to protect against CSRF Attacks is to specify the SameSite Attribute on cookies. A server can specify the SameSite attribute when setting a cookie to indicate that the cookie should not be sent when coming from external sites.
Spring Security does not directly control the creation of the session cookie, so it does not provide support for the SameSite attribute. Spring Session provides support for the SameSite attribute in servlet-based applications. Spring Framework’s CookieWebSessionIdResolver provides out of the box support for the SameSite attribute in WebFlux-based applications.
An example, of an HTTP response header with the SameSite attribute might look like:
Valid values for the SameSite attribute are:
Strict : When specified, any request coming from the same-site includes the cookie. Otherwise, the cookie is not included in the HTTP request.
Lax : When specified, cookies are sent when coming from the same-site or when the request comes from top-level navigations and the method is idempotent. Otherwise, the cookie is not included in the HTTP request.
Consider how our example could be protected using the SameSite attribute. The bank application can protect against CSRF by specifying the SameSite attribute on the session cookie.
With the SameSite attribute set on our session cookie, the browser continues to send the JSESSIONID cookie with requests coming from the banking website. However, the browser no longer sends the JSESSIONID cookie with a transfer request coming from the evil website. Since the session is no longer present in the transfer request coming from the evil website, the application is protected from the CSRF attack.
There are some important considerations to be aware of when using SameSite attribute to protect against CSRF attacks.
Setting the SameSite attribute to Strict provides a stronger defense but can confuse users. Consider a user who stays logged into a social media site hosted at social.example.com. The user receives an email at email.example.org that includes a link to the social media site. If the user clicks on the link, they would rightfully expect to be authenticated to the social media site. However, if the SameSite attribute is Strict , the cookie would not be sent and so the user would not be authenticated.
We could improve the protection and usability of SameSite protection against CSRF attacks by implementing gh-7537.
Another obvious consideration is that, in order for the SameSite attribute to protect users, the browser must support the SameSite attribute. Most modern browsers do support the SameSite attribute. However, older browsers that are still in use may not.
For this reason, we generally recommend using the SameSite attribute as a defense in depth rather than the sole protection against CSRF attacks.
When to use CSRF protection
When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are creating a service that is used only by non-browser clients, you likely want to disable CSRF protection.
CSRF protection and JSON
A common question is “do I need to protect JSON requests made by JavaScript?” The short answer is: It depends. However, you must be very careful, as there are CSRF exploits that can impact JSON requests. For example, a malicious user can create a CSRF with JSON by using the following form:
This produces the following JSON structure
If an application were not validating the Content-Type header, it would be exposed to this exploit. Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with .json , as follows:
CSRF and Stateless Browser Applications
What if my application is stateless? That does not necessarily mean you are protected. In fact, if a user does not need to perform any actions in the web browser for a given request, they are likely still vulnerable to CSRF attacks.
For example, consider an application that uses a custom cookie that contains all the state within it for authentication (instead of the JSESSIONID). When the CSRF attack is made, the custom cookie is sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example. This application is vulnerable to CSRF attacks.
Applications that use basic authentication are also vulnerable to CSRF attacks. The application is vulnerable since the browser automatically includes the username and password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example.
CSRF Considerations
There are a few special considerations to consider when implementing protection against CSRF attacks.
Logging In
To protect against forging login requests, the login HTTP request should be protected against CSRF attacks. Protecting against forging login requests is necessary so that a malicious user cannot read a victim’s sensitive information. The attack is performed as follows:
A malicious user performs a CSRF login with the malicious user’s credentials. The victim is now authenticated as the malicious user.
The malicious user then tricks the victim into visiting the compromised website and entering sensitive information.
The information is associated to the malicious user’s account so the malicious user can log in with their own credentials and view the victim’s sensitive information.
A possible complication to ensuring login HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. A session timeout is surprising to users who do not expect to need to have a session to log in. For more information refer to CSRF and Session Timeouts.
Logging Out
To protect against forging logout requests, the logout HTTP request should be protected against CSRF attacks. Protecting against forging logout requests is necessary so that a malicious user cannot read a victim’s sensitive information. For details on the attack, see this blog post.
A possible complication to ensuring logout HTTP requests are protected against CSRF attacks is that the user might experience a session timeout that causes the request to be rejected. A session timeout is surprising to users who do not expect to have a session to log out. For more information, see CSRF and Session Timeouts.
CSRF and Session Timeouts
More often than not, the expected CSRF token is stored in the session. This means that, as soon as the session expires, the server does not find an expected CSRF token and rejects the HTTP request. There are a number of options (each of which come with trade offs) to solve timeouts:
The best way to mitigate the timeout is by using JavaScript to request a CSRF token on form submission. The form is then updated with the CSRF token and submitted.
Another option is to have some JavaScript that lets the user know their session is about to expire. The user can click a button to continue and refresh the session.
Finally, the expected CSRF token could be stored in a cookie. This lets the expected CSRF token outlive the session.
One might ask why the expected CSRF token is not stored in a cookie by default. This is because there are known exploits in which headers (for example, to specify the cookies) can be set by another domain. This is the same reason Ruby on Rails no longer skips a CSRF checks when the header X-Requested-With is present. See this webappsec.org thread for details on how to perform the exploit. Another disadvantage is that by removing the state (that is, the timeout), you lose the ability to forcibly invalidate the token if it is compromised.
Multipart (file upload)
Protecting multipart requests (file uploads) from CSRF attacks causes a chicken or the egg problem. To prevent a CSRF attack from occurring, the body of the HTTP request must be read to obtain the actual CSRF token. However, reading the body means that the file is uploaded, which means an external site can upload a file.
There are two options to using CSRF protection with multipart/form-data:
Each option has its trade-offs.
Before you integrate Spring Security’s CSRF protection with multipart file upload, you should first ensure that you can upload without the CSRF protection. More information about using multipart forms with Spring, see the 1.1.11. Multipart Resolver section of the Spring reference and the MultipartFilter Javadoc.
Place CSRF Token in the Body
The first option is to include the actual CSRF token in the body of the request. By placing the CSRF token in the body, the body is read before authorization is performed. This means that anyone can place temporary files on your server. However, only authorized users can submit a file that is processed by your application. In general, this is the recommended approach, because the temporary file upload should have a negligible impact on most servers.
Include CSRF Token in URL
If letting unauthorized users upload temporary files is not acceptable, an alternative is to include the expected CSRF token as a query parameter in the action attribute of the form. The disadvantage to this approach is that query parameters can be leaked. More generally, it is considered best practice to place sensitive data within the body or headers to ensure it is not leaked. You can find additional information in RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s.
HiddenHttpMethodFilter
Some applications can use a form parameter to override the HTTP method. For example, the following form can treat the HTTP method as a delete rather than a post .
Overriding the HTTP method occurs in a filter. That filter must be placed before Spring Security’s support. Note that overriding happens only on a post , so this is actually unlikely to cause any real problems. However, it is still best practice to ensure that it is placed before Spring Security’s filters.
Spring Security 4 + CSRF (добавление в Spring проект защиты от межсайтовой подделки запроса)

Здравствуйте!
Современное веб приложение считается уязвимым, если в нем отсутствует защита от Межсайтовой подделки запроса (CSRF).
В Spring Security 4.x она включена по умолчанию, поэтому при миграции с Spring Security 3.x на 4.x ее надо либо отключить
либо, правильнее и зачетнее, добавить в проект.Собственно, сделал это в 10-минутном видео:
Ниже приведу основные моменты внедрения CSRF в проект:
- Использовать правильные HTTP запросы: по умолчанию CSRF защита отсутствует для запросов GET, HEAD, TRACE, OPTIONS. Это в частности означает, что для logout, если мы не хотим, чтобы злоумышленный сайт мог разлогинить пользователя, авторизованного в нашем приложении, требуется запрос POST.
- Во всех формах, где есть submit, добавить скрытое поле name=_csrf со значением csrfToken. Проще всего это сделать через Spring’s form tag library, который, кроме биндинга и валидации, при включенном csrf подставит в форму требуемое скрытое поле.
Cross Site Request Forgery (CSRF) for Servlet Environments
This section discusses Spring Security’s Cross Site Request Forgery (CSRF) support for servlet environments.
Using Spring Security CSRF Protection
The steps to using Spring Security’s CSRF protection are outlined below:
Use proper HTTP verbs
The first step to protecting against CSRF attacks is to ensure that your website uses proper HTTP verbs. This is covered in detail in Safe Methods Must be Idempotent.
Configure CSRF Protection
The next step is to configure Spring Security’s CSRF protection within your application. Spring Security’s CSRF protection is enabled by default, but you may need to customize the configuration. The next few sections cover a few common customizations.
Custom CsrfTokenRepository
By default, Spring Security stores the expected CSRF token in the HttpSession by using HttpSessionCsrfTokenRepository . There can be cases where users want to configure a custom CsrfTokenRepository . For example, it might be desirable to persist the CsrfToken in a cookie to support a JavaScript-based application.
By default, the CookieCsrfTokenRepository writes to a cookie named XSRF-TOKEN and reads it from a header named X-XSRF-TOKEN or the HTTP parameter _csrf . These defaults come from AngularJS.
You can configure CookieCsrfTokenRepository in XML byusing the following:
The sample explicitly sets cookieHttpOnly=false . This is necessary to allow JavaScript (such as AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, we recommend omitting cookieHttpOnly=false to improve security.
You can configure CookieCsrfTokenRepository in Java or Kotlin configuration by using:
The sample explicitly sets cookieHttpOnly=false . This is necessary to let JavaScript (such as AngularJS) read it. If you do not need the ability to read the cookie with JavaScript directly, we recommend omitting cookieHttpOnly=false (by using new CookieCsrfTokenRepository() instead) to improve security.
Disable CSRF Protection
By default, CSRF protection is enabled. However, you can disable CSRF protection if it makes sense for your application.
The following XML configuration disables CSRF protection:
The following Java or Kotlin configuration disables CSRF protection:
Configure CsrfTokenRequestHandler
Spring Security’s CsrfFilter exposes a CsrfToken as an HttpServletRequest attribute named _csrf with the help of a CsrfTokenRequestHandler. In 5.8, the default implementation was CsrfTokenRequestAttributeHandler which simply makes the _csrf attribute available as a request attribute.
As of 6.0, the default implementation is XorCsrfTokenRequestAttributeHandler , which provides protection for BREACH (see gh-4001).
If you wish to disable BREACH protection of the CsrfToken and revert to the 5.8 default, you can configure CsrfTokenRequestAttributeHandler in XML using the following:
You can configure CsrfTokenRequestAttributeHandler in Java Configuration using the following:
Include the CSRF Token
For the synchronizer token pattern to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. 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.
We’ve seen that the CsrfToken is exposed as a request attribute. This means that any view technology can access the CsrfToken to expose the expected token as either a form or meta tag. Fortunately, there are integrations listed later in this chapter that make including the token in form and ajax requests even easier.
Form URL Encoded
To post an HTML form, the CSRF token must be included in the form as a hidden input. For example, the rendered HTML might look like:
Next, we discuss various ways of including the CSRF token in a form as a hidden input.
Automatic CSRF Token Inclusion
Spring Security’s CSRF support provides integration with Spring’s RequestDataValueProcessor through its CsrfRequestDataValueProcessor . This means that, if you use Spring’s form tag library, Thymeleaf, or any other view technology that integrates with RequestDataValueProcessor , then forms that have an unsafe HTTP method (such as post) automatically include the actual CSRF token.
csrfInput Tag
If you use JSPs, you can use Spring’s form tag library. However, if that is not an option, you can also include the token with the csrfInput tag.
CsrfToken Request Attribute
If the other options for including the actual CSRF token in the request do not work, you can take advantage of the fact that the CsrfToken is exposed as an HttpServletRequest attribute named _csrf .
The following example does this with a JSP:
Ajax and JSON Requests
If you use JSON, you cannot submit the CSRF token within an HTTP parameter. Instead, you can submit the token within a HTTP header.
The following sections discuss various ways of including the CSRF token as an HTTP request header in JavaScript based applications.
Automatic Inclusion
You can configure Spring Security to store the expected CSRF token in a cookie. By storing the expected CSRF in a cookie, JavaScript frameworks, such as AngularJS, automatically include the actual CSRF token in the HTTP request headers.
Meta Tags
An alternative pattern to exposing the CSRF in a cookie is to include the CSRF token within your meta tags. The HTML might look something like this:
Once the meta tags contain the CSRF token, the JavaScript code can read the meta tags and include the CSRF token as a header. If you use jQuery, you can do this with the following code:
csrfMeta tag
If you use JSPs, one way to write the CSRF token to the meta tags is by using the csrfMeta tag.
CsrfToken Request Attribute
If the other options for including the actual CSRF token in the request do not work, you can take advantage of the fact that the CsrfToken is exposed as an HttpServletRequest attribute named _csrf . The following example does this with a JSP:
CSRF Considerations
There are a few special considerations to consider when implementing protection against CSRF attacks. This section discusses those considerations as they pertain to servlet environments. See CSRF Considerations for a more general discussion.
Logging In
It is important to require CSRF for log in requests to protect against forging log in attempts. Spring Security’s servlet support does this out of the box.
Logging Out
It is important to require CSRF for log out requests to protect against forging logout attempts. If CSRF protection is enabled (the default), Spring Security’s LogoutFilter to only process HTTP POST. This ensures that logging out requires a CSRF token and that a malicious user cannot forcibly log out your users.
The easiest approach is to use a form to log out. If you really want a link, you can use JavaScript to have the link perform a POST (maybe on a hidden form). 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.
If you really want to use HTTP GET with logout, you can do so. However, remember that this is generally not recommended. For example, the following Java Configuration logs out when the /logout URL is requested with any HTTP method:
CSRF and Session Timeouts
By default, Spring Security stores the CSRF token in the HttpSession . This can lead to a situation where the session expires, leaving no CSRF token to validate against.
We have already discussed general solutions to session timeouts. This section discusses the specifics of CSRF timeouts as it pertains to the servlet support.
You can change the storage of the CSRF token to be in a cookie. For details, see the Custom CsrfTokenRepository section.
If a token does expire, you might want to customize how it is handled by specifying a custom AccessDeniedHandler . The custom AccessDeniedHandler can process the InvalidCsrfTokenException any way you like. For an example of how to customize the AccessDeniedHandler , see the provided links for both xml and Java configuration.
Multipart (file upload)
We have already discussed how protecting multipart requests (file uploads) from CSRF attacks causes a chicken and the egg problem. This section discusses how to implement placing the CSRF token in the body and url within a servlet application.
You can find more information about using multipart forms with Spring in the 1.1.11. Multipart Resolver section of the Spring reference and the MultipartFilter javadoc.
Place CSRF Token in the Body
We have already discussed the tradeoffs of placing the CSRF token in the body. In this section, we discuss how to configure Spring Security to read the CSRF from the body.
To read the CSRF token from the body, the MultipartFilter is specified before the Spring Security filter. 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. However, only authorized users can submit a file that is processed by your application. In general, this is the recommended approach because the temporary file upload should have a negligible impact on most servers.
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:
To ensure MultipartFilter is specified before the Spring Security filter with XML configuration, users can ensure the <filter-mapping> element of the MultipartFilter is placed before the springSecurityFilterChain within the web.xml as shown below:
Include a CSRF Token in a URL
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. Since the CsrfToken is exposed as an HttpServletRequest request attribute, we can use that to create an action with the CSRF token in it. The following example does this with a JSP:
HiddenHttpMethodFilter
We have already discussed the trade-offs of placing the CSRF token in the body.
In Spring’s Servlet support, overriding the HTTP method is done by using HiddenHttpMethodFilter . You can find more information in the HTTP Method Conversion section of the reference documentation.