How to disable CSRF in Spring Security 4 only for specific URL pattern through XML configuration?

后端 未结 2 635
悲哀的现实
悲哀的现实 2020-12-30 16:02

How to disable CSRF in Spring Security 4 only for specific URL pattern through XML configuration?

Spring-security.xml



        
相关标签:
2条回答
  • 2020-12-30 16:23

    You can have two (or more) filter chains:

    <http pattern="/your-specific/**">
      <!-- ... -->
      <csrf disabled="true"/>
    </http>
    <http>
      <!-- ... -->
    </http>
    
    0 讨论(0)
  • 2020-12-30 16:32

    Could not achieve with just XML changes. Below worked for me

    Change in Spring-security.xml

    <security:http  use-expressions="true" authentication-manager-ref="authenticationManager">
        <security:intercept-url pattern="/auth/**" access="hasAnyRole('ROLE_USER')" />
        <security:form-login login-page="/login" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-url="/login" login-processing-url="/j_spring_security_check" />
        <security:logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutSuccessHandler" />
    
        <security:csrf request-matcher-ref="csrfSecurityRequestMatcher"  />
    </security:http>
    

    CsrfSecurityRequestMatcher

    public class CsrfSecurityRequestMatcher implements RequestMatcher {
        private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
        private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("/ext/**", null);
    
        @Override
        public boolean matches(HttpServletRequest request) {          
            if(allowedMethods.matcher(request.getMethod()).matches()){
                return false;
            }
            return !unprotectedMatcher.matches(request);
        }
    }
    
    0 讨论(0)
提交回复
热议问题