5

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?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 1
    It seems like your application is reactive, based on the logs `Created new WebSession`. You do not configure security in reactive applications by extending `WebSecurityConfigurerAdapter`. See https://stackoverflow.com/questions/67268107/cannot-access-javax-servlet-filter-error-when-using-spring-security-with-sprin/67269039#67269039 – Eleftheria Stein-Kousathana May 03 '21 at 08:20
  • 2
    Hi Peter, did you resolve this issue? – bijayshrestha Jun 12 '22 at 03:17

2 Answers2

0

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.

T Rachana
  • 1
  • 1
0

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);
    };
}
Sagir
  • 21
  • 1
  • 9