Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not verify the provided CSRF token because your session was not found in spring security

I am using spring security along with java config

@Override protected void configure(HttpSecurity http) throws Exception {      http     .authorizeRequests()     .antMatchers("/api/*").hasRole("ADMIN")     .and()     .addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class)     .exceptionHandling()     .authenticationEntryPoint(restAuthenticationEntryPoint)     .and()     .formLogin()     .successHandler(authenticationSuccessHandler)     .failureHandler(new SimpleUrlAuthenticationFailureHandler()); 

I am using PostMan for testing my REST services. I get 'csrf token' successfully and I am able to login by using X-CSRF-TOKEN in request header. But after login when i hit post request(I am including same token in request header that i used for login post request) I get the following error message:

HTTP Status 403 - Could not verify the provided CSRF token because your session was not found.

Can any one guide me what I am doing wrong.

like image 960
Haseeb Wali Avatar asked Jun 24 '16 00:06

Haseeb Wali


People also ask

What is CSRF token in Spring Security?

CSRF (Cross Site Request Forgery) is a technique in which an attacker attempts to trick you into performing an action using an existing session of a different website. Spring Security when combined with Thymeleaf templates, automatically inserts a token into all web forms as a hidden field.

What is CSRF disable in Spring Security?

But till now in all our examples we had disabled CSRF. CSRF stands for Cross-Site Request Forgery. It is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.


1 Answers

According to spring.io:

When should you use CSRF protection? Our recommendation is to 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.

So to disable it:

@Configuration public class RestSecurityConfig extends WebSecurityConfigurerAdapter {   @Override   protected void configure(HttpSecurity http) throws Exception {     http.csrf().disable();   } } 

Note: CSRF protection is enabled by default with Java Configuration

like image 52
developerick Avatar answered Sep 27 '22 16:09

developerick