问题
CSRF protection is used so that any requests made from other websites cannot affect my website to cause harm. It is said in the spring security csrf documentation that csrf is applied for put post patch delete requests.
But according to my understanding, login/signup forms do not need csrf protection, as they already require credentials in the form of username and password and even if such a request is made from another website, there will be no harm as the user will just get logged in.
But since login is usually a post request, csrf will automatically be applied here by spring default. Which means I will need to add the csrf token generation parameters as hidden input field to my form like so:
<form th:action="@{/login}" method="post">
<fieldset>
<input type="hidden"
th:name="${_csrf.parameterName}"
th:value="${_csrf.token}" />
</fieldset>
...
</form>
If I dont add this, 403 Forbidden error will come. But if I disable this csrf like so..:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
Then all the pages lose the csrf protection in the website. How can I apply csrf to certain pages and not to others, even though they are making post requests?
I am using Spring Boot + Spring Security + thymeleaf
回答1:
You may use .csrf().ignoringAntMatchers("/login")
in configure(HttpSecurity http)
csrf().ignoringAntMatchers("String")
Allows specifying HttpServletRequest that should not use CSRF Protectioneven if they match the requireCsrfProtectionMatcher(RequestMatcher).
For example, the following configuration will ensure CSRF protection ignores:
- Any GET, HEAD, TRACE, OPTIONS (this is the default)
- We also explicitly state to ignore any request that starts with "/sockjs/"
http
.csrf()
.ignoringAntMatchers("/sockjs/**")
.and()
...
.csrf().ignoringRequestMatchers(requestMatchers)
Allows specifying HttpServletRequests that should not use CSRF Protectioneven if they match the requireCsrfProtectionMatcher(RequestMatcher).
For example, the following configuration will ensure CSRF protection ignores:
- Any GET, HEAD, TRACE, OPTIONS (this is the default)
- We also explicitly state to ignore any request that has a "X-Requested-With: XMLHttpRequest" header
http
.csrf()
.ignoringRequestMatchers(request -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
.and()
来源:https://stackoverflow.com/questions/57056823/how-to-disable-csrf-protection-for-particular-pages-in-my-website