繁体   English   中英

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

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

如何在WebFilter环境中的 WebFilter 中访问安全上下文/authenticton object?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM