Why I recieve invalid csrf token?

46.5k Views Asked by At

I have a project with spring-cloud-security. It's a auth server for oauth authorization. It's worked fine in the past.

I add spring profile for ssl support with cofiguration:

security:
  require-ssl: true
server:
  ssl:
    key-store: dev.p12
    key-store-password: devpass
    keyStoreType: PKCS12
    keyAlias: calc

With this profile, authentication works fine, but when I disable it and go to login via http, authentication breaks down.

o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8090/login

How can I fix it?

1

There are 1 best solutions below

2
On

Your server has CSRF enabled. The @EnableWebSecurity annotation will enable CSRF by default as stated in the documentation.

CSRF protection is enabled by default with Java configuration.

There are two ways to "fix" this, either disable CSRF or submit the CSRF-token when doing PATCH, POST, PUT, and DELETE actions.

To disable CSRF do it in the Spring Security configuration

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}

To submit the CSRF-token you must include it in the request to the server (in this example a JSP with sending a POST request)

<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}" method="post">
  <input type="submit" value="Log out" />
  <input type="hidden" name="${_csrf.parameterName}"
    value="${_csrf.token}"/>
</form>

All examples taken from the Spring Cross Site Request Forgery (CSRF) documentation

Please consider the recommendation from Spring when considering whether to disable CSRF

[...] use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.