[英]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.