Failed to validate provided CSRF token because your session was not found in spring security

I use 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 use PostMan to test my REST services. I get "csrf token" successfully, and I can log in using X-CSRF-TOKEN in the request header. But after logging in, when I delete the post request (I include the same token in the request header that I used for the login request). I get the following error message:

HTTP Status 403 - The provided CSRF token could not be verified because your session was not found.

Can someone explain to me what I'm doing wrong.

+40
java spring-security csrf spring-restcontroller
Jun 24. '16 at 0:44
source share
7 answers

According to spring.io:

When should CSRF protection be used? We recommend using CSRF protection for any request that can be processed by the browser by ordinary users. If you only create a service that is used by non-browser clients, you probably 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 in the Java configuration.

+72
Sep 15 '16 at 11:17
source share

Disabling CSRF protection is a bad idea.

Spring automatically generates a new CSRF token after each request, and you need to include it in all HTTP requests with side effects (PUT, POST, PATCH, DELETE).

In Postman, you can use the test in each request to store the CSRF token globally, for example, when using CookieCsrfTokenRepository

 pm.globals.set("xsrf-token", postman.getResponseCookie("XSRF-TOKEN").value); 

And then {{xsrf-token}} it as a header with the key X-XSRF-TOKEN and the value {{xsrf-token}} .

+2
May 21 '18 at 13:28
source share

try this: @Override protected boolean sameOriginDisabled() { return true;}

 @Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { ... // Determines if a CSRF token is required for connecting. This protects against remote // sites from connecting to the application and being able to read/write data over the // connection. The default is false (the token is required). @Override protected boolean sameOriginDisabled() { return true; } } 

source: WebSocket Security: disable CSRF in WebSockets

+2
Jul 10 '18 at 20:17
source share

I had the same problem, the same result: "The provided CSRF token could not be verified because your session was not found."

But, in my case, I make two requests, and the second request (POST) does not work.

The code is here:

 private List<Mandado> pesquisaExterna(Pessoa pessoa) throws UnsupportedEncodingException, IOException, URISyntaxException { this.httpClient = HttpClientBuilder.create().build(); /* Estabelecendo a Sessão */ Gson gson = new Gson(); this.httpContext = HttpClientContext.create(); CookieStore cookieStore = new BasicCookieStore(); this.httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); HttpPost post_auth = new HttpPost(this.URL_AUTENTICAR); // URL para request StringEntity postingString = new StringEntity(gson.toJson(this.authenticationRequestDTO)); // Objeto para POST post_auth.setEntity(postingString); post_auth.addHeader("content-type", MediaType.APPLICATION_JSON_VALUE); // definindo os headers post_auth.addHeader("cache-control", "no-cache"); System.out.println("body: " + gson.toJson(this.authenticationRequestDTO)); HttpResponse response; ObjectMapper mapper = new ObjectMapper(); AuthenticationResponseDTO auth = new AuthenticationResponseDTO(); String cookie = ""; String result = ""; try { response = this.httpClient.execute(post_auth, this.httpContext); String resp = MandadoBusiness.convertStreamToString(response.getEntity().getContent()); System.out.println("resp1: " + resp); JsonNode authentication = mapper.readTree(resp); PessoaFilter filter = new PessoaFilter(); if (pessoa.getNrCpf() != null && pessoa.getNrCpf().length() == 11) { DocumentoDTO doc = new DocumentoDTO(); doc.setNumero(pessoa.getNrCpf()); filter.setDocumento(doc); } List<NameValuePair> postParameters = new ArrayList<>(); //parâmetros do request postParameters.add(new BasicNameValuePair("page", "1")); postParameters.add(new BasicNameValuePair("size", "30")); URIBuilder uriBuilder = new URIBuilder(this.URL + "/api/pessoas/filter"); uriBuilder.addParameters(postParameters); HttpPost post = new HttpPost(uriBuilder.build()); // URL para request postingString = new StringEntity(gson.toJson(filter)); // Objeto para POST post.setEntity(postingString); post.addHeader("content-type", MediaType.APPLICATION_JSON_VALUE); // definindo os headers post.addHeader("Cookie", authentication.get("token_csrf").asText()); post.addHeader("X-XSRF-TOKEN", authentication.get("token_csrf").asText()); post.addHeader("Authorization", "Bearer " + authentication.get("token_jwt").asText()); // IMPRESSÃO DOS DETALHES DO REQUEST FEITO System.out.println("body: " + gson.toJson(filter)); System.out.println("headers: " + Arrays.toString(post.getAllHeaders())); System.out.println("request_line: " + post.getRequestLine().toString()); response = this.httpClient.execute(post,this.httpContext); if(response.getEntity() != null){ result = MandadoBusiness.convertStreamToString(response.getEntity().getContent()); System.out.println("Response: " + result); }else{ System.out.println("Response with error!!"); } } catch (IOException | UnsupportedOperationException e) { System.out.println("Msg: " + e.getMessage()); } return gson.fromJson(result, ArrayList.class); } 

Someone can help - do I understand the error?

Please excuse my awful English!

0
Dec 10 '18 at 20:10
source share

I came to the same error only with POST methods, received 403 Forbidden "The provided CSRF token could not be verified because your session was not found."

Having studied for some time, I found a solution by adding the @EnableResourceServer annotation to the configuration.

Config looks like this (spring-boot.version → 1.4.1.RELEASE, spring-security.version → 4.1.3.RELEASE, spring.version → 4.3.4.RELEASE)

 @Configuration @EnableWebSecurity @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends ResourceServerConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(inMemoryUserDetailsManager()).passwordEncoder(passwordEncoder()); } @Override public void configure(HttpSecurity http) throws Exception { http.httpBasic(); http.sessionManagement().sessionCreationPolicy(STATELESS); http.csrf().disable(); http.authorizeRequests().anyRequest() .permitAll(); } private InMemoryUserDetailsManager inMemoryUserDetailsManager() throws IOException { // load custom properties Properties properties = new Properties(); return new InMemoryUserDetailsManager(properties); } private PasswordEncoder passwordEncoder() { return new TextEncryptorBasedPasswordEncoder(textEncryptor()); } private TextEncryptor textEncryptor() { return new OpenSslCompatibleTextEncryptor(); } } 
0
Jun 18 '19 at 11:21
source share

I get this error message ( HTTP Status 403 - Could not verify the provided CSRF token because your session was not found. ) When I make an AJAX JS call to fetch without using the credentials: "same-origin" parameter.

Wrong way

 fetch(url) .then(function (response) { return response.json(); }) .then(function (data) { console.log(data); }) 

The right way

 fetch(url, { credentials: "same-origin" }) .then(function (response) { return response.json(); }) .then(function (data) { console.log(data); }) 
0
Jul 25 '19 at 10:28
source share

I solved this by adding the last attribute to my login page, it may be beneficial.

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%> 
-four
Jun 30 '16 at 6:30
source share



All Articles