CSRF needs to be disabled for /login spring security

Viewed 1626

All of my REST interfaces work fine with csrf protection enabled but I need to disable csrf for /login otherwise I get an 403 Forbidden. I use spring security, the login path is available through spring security.

http.csrf().disable() 

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

Or if it is not a problem to disable CSRF on the login page the problem would also be fixed

EDIT:

.csrf().ignoringAntMatchers("/login")

The login route always needs an login body so there should be no CSRF attack potential, isn't?

2 Answers

if you don't use spring mvc form tags , you can't use spring security csrf support automatically, probably you use plain html form tags that's why you get http 403, you need to manually include csrf token in your form submission.

Either you need to use spring mvc form tags like this

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
…
<form:form action="" method="POST">
…
</form:form> 

or adding csrf token in your plain html form submission manually.

<form action="" method="POST">
<input type="hidden" name="${_csrf.parameterName}" value = "${_csrf.token}" />
…
</form> 

Try this out:

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);
    }
}
Related