如何在 Spring webflux 中获取 WebFilter 中的身份验证上下文?

How to get the Authentication context inside WebFilter in Spring webflux?

如何在 webflux 环境中访问 WebFilter 中的安全上下文/验证对象?

这里的问题是 SecurityContextHolder.getContext().getAuthentication() 始终为空,即使对于经过身份验证的用户也是如此。

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public WebFilter loggingFilter() {
    return new WebFilter() {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            SecurityContextHolder.getContext().getAuthentication();
            //apply some custom logic based on the authentication
            
            //then continue
            return chain.filter(exchange);
        }
    };
}

我试过我可以在 @GetMapping 方法中成功访问上下文,如下所示:

@GetMapping("/ok")
public Mono<String> ok() {
    return ReactiveSecurityContextHolder.getContext()
            .flatMap(s -> {
                System.out.println(s.getAuthentication());
                return Mono.just("OK");
            });
}

但是我怎样才能将它集成到 WebFilter 中呢?

根据@Toerktumlare 的提示,我可以按如下方式解决我的问题:

return ReactiveSecurityContextHolder.getContext()
        .doOnNext((sc) -> {
            if (sc.getAuthentication() != null)
                //custom logic on sc.getAuthentication().getName()
        })
        .then(chain.filter(exchange));