scpting security requireCsrfProtectionMatcher with

2019-08-13 03:56发布

I am trying to disable Csrf for specific url. here is what i have done so far:

public HttpSessionCsrfTokenRepository csrfTokenRepository() {
    final HttpSessionCsrfTokenRepository tokenRepository = new HttpSessionCsrfTokenRepository();
    tokenRepository.setHeaderName("X-XSRF-TOKEN");
    return tokenRepository;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    RequestMatcher matcher = request -> !("//j_spring_cas_security_check".equals(request.getRequestURI()));
    http.csrf()
            .requireCsrfProtectionMatcher(matcher)
            .csrfTokenRepository(csrfTokenRepository());

If i comment out requireCsrfProtectionMatcher or simply return false in all matchers there will be no errors, but with this config it gives me:

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.

I need to disable csrf on j_spring_cas_security_check so that single sign out works and tokenRepository to work with angularjs. Is there anything i am missing?

1条回答
forever°为你锁心
2楼-- · 2019-08-13 04:08

If you don't pass anything to requireCsrfProtectionMatcher, the default behaviour is to bypass all GET requests. The moment explicitly provide a new one, the behaviour is lost and you will check requests for GET as well. Change the code to following to allow GET requests.

public class CsrfRequestMatcher implements RequestMatcher {

    // Always allow the HTTP GET method
    private Pattern allowedMethods = Pattern.compile("^GET$");

    @Override
    public boolean matches(HttpServletRequest request) {

        if (allowedMethods.matcher(request.getMethod()).matches()) {
            return false;
        }

        // Your logic goes here


        return true;
    }

}
查看更多
登录 后发表回答