How to disable csrf protection for particular pages in my website?

主宰稳场 提交于 2021-01-28 22:18:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!