Peter Penzov
Peter Penzov

Reputation: 1682

An expected CSRF token cannot be found

I'm trying to disable Spring security into latest Spring Cloud using this configuration:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Order(SecurityProperties.DEFAULT_FILTER_ORDER)
public class WebSecurityConfigSec extends WebSecurityConfigurerAdapter {

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

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/**");
    }
}

application.yml

spring:
    main:
        allow-bean-definition-overriding: true
security:
    ignored=/**:
    enable-csrf: false

I also tried to add:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

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

But it's not working.

I get error: An expected CSRF token cannot be found

18:16:24.537 [boundedElastic-2] DEBUG DefaultWebSessionManager[lambda$createWebSession$3:94] - Created new WebSession.
18:16:24.540 [boundedElastic-2] DEBUG HttpWebHandlerAdapter[traceDebug:91] - [1ffd0a30] Completed 403 FORBIDDEN

Do you know how I can solve this issue?

Upvotes: 5

Views: 16882

Answers (3)

Allen Sun
Allen Sun

Reputation: 1

may be you pom.xml have a dependency confict,such as dependency about "oauth2"

Upvotes: 0

Sagir
Sagir

Reputation: 19

I Fixed this by

    @Bean
  SecurityWebFilterChain springSecurityFilterChain(
    ServerHttpSecurity http,
    ReactiveClientRegistrationRepository clientRegistrationRepository
){
return http
...
.csrf(csrf -> csrf.csrfTokenRepository(
  CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
.build(); 
}

@Bean
WebFilter csrfWebFilter() {
//A filter with the only purpose of subscribing to the CsrfToken reactive stream and ensuring its value is extracted correctly
    return (exchange, chain) -> {
      exchange.getResponse().beforeCommit(() -> Mono.defer(() -> {
        Mono<CsrfToken> csrfToken =
          exchange.getAttribute(CsrfToken.class.getName());
        return csrfToken != null ? csrfToken.then() : Mono.empty();
      }));
      return chain.filter(exchange);
    };
}

Upvotes: -1

Rachana Tirumanyam
Rachana Tirumanyam

Reputation: 24

Exclude the MVC dependencies from pom.xml

And add:

spring:
 main:
  web-application-type: reactive

This worked for me; I was getting CSRF error as spring security used in Spring MVC was enabled.

Upvotes: -1

Related Questions