簡體   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