Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webflux disable CSRF on specific URLs

The idea is to replicate http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/ in webflux.

This is where I got so far:

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http) {
        http
           .csrf().requireCsrfProtectionMatcher(
                  new ServerWebExchangeMatcher() {

                    @Override
                    public Mono<MatchResult> matches(ServerWebExchange serverWebExchange) {
                    // here check if the url should have csrf or not and then return MatchResult.match() or notMatch(), however I find that if I return match then I get 'Invalid CSRF Token' error.
                    //    return MatchResult.match();
                    //    return MatchResult.notMatch();
                    }
                }
                ).and()
                .anyExchange().authenticated()
                .and()
                .httpBasic()
                .and()
                .formLogin().loginPage("/login")
                .and().logout()

        return http.build();
    }
}
like image 868
Grego Avatar asked Feb 19 '26 16:02

Grego


1 Answers

This should do it

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http) {
        http
           .csrf().requireCsrfProtectionMatcher(
                  new ServerWebExchangeMatcher() {

                    @Override
                    public Mono<MatchResult> matches(ServerWebExchange serverWebExchange) {
                        ServerWebExchangeMatchers.pathMatchers("/urls-with-csrf-check/**").matches(serverWebExchange)
                    }
                }
                ).and()
                .anyExchange().authenticated()
                .and()
                .httpBasic()
                .and()
                .formLogin().loginPage("/login")
                .and().logout()

        return http.build();
    }
like image 104
McGin Avatar answered Feb 21 '26 13:02

McGin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!