Webflux禁用特定URL上的CSRF

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Webflux禁用特定URL上的CSRF相关的知识,希望对你有一定的参考价值。

想法是在webflux中复制http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/

这是我到目前为止的地方:

@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();
    

答案

这应该做到这一点

    @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();
    
另一答案

config allowedOrigins:

@Bean
public WebFluxConfigurer corsConfigurer() 
    return new WebFluxConfigurerComposite() 

        @Override
        public void addCorsMappings(CorsRegistry registry) 
            registry
                .addMapping("/**")
                .allowedOrigins("/goodss")
                .allowedMethods("*");
        
    ;

以上是关于Webflux禁用特定URL上的CSRF的主要内容,如果未能解决你的问题,请参考以下文章

Spring Webflux:将服务器发送事件推送给特定用户

禁用执行器健康端点的 webflux(反应式)安全性

Web上的Webflux嵌套路由器始终返回404

为特定请求/URL/端点禁用登录 gunicorn

禁用传输编码:在 Spring Webflux 响应中分块

将 spring-security 与 spring-webflux 一起使用时禁用 WebSession 创建