February 02, 2018

How to resolve could not verify the provided CSRF token?

We recently deployed Spring Boot war on Jboss EAP 6.4. While calling the one of the Rest Webservice we were getting, "HTTP Status 403 – Could not verify the provided CSRF token because your session was not found."

Possible solution to resolve this issue are:
1). Disable CSRF token in spring security.
2). Pass CSRF token from login page

We disabled CSRF token and now the webservice is working fine. Here are the ways you can disable the CSRF token:

1.1). As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below.

 < http >
     < ...... >
     < csrf disabled="true"/ >
     < ...... >
 < /http >


1.2). by calling the disable method.
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Inject private SecurityProperties securityProperties;

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



If you want to pass the CSRF token:
     < form method="post" action="/login" >
        User Name :  < input type="text" name="username" >
        Password :  < input type="password" name="password" >
         < input type="hidden"
               name="${_csrf.parameterName}"
               value="${_csrf.token}"/ >
         < input name="submit" value="Login" type="submit"/ >
     < /form >

   
-K Himaanshu Shuklaa..

No comments:

Post a Comment