簡體   English   中英

在 Spring 雲網關前置過濾器中獲取 SecurityContextHolder

[英]Getting SecurityContextHolder in Spring Cloud Gateway Pre Filter

我在 Spring 引導項目(版本 2.2.6)中使用 Spring 雲網關和 Spring 安全性。 我有一個自定義的 Pre 過濾器,它需要在將請求轉發到下游服務之前向請求添加標頭。 Pre 過濾器需要讀取 Spring Security's Authentication object 以獲取權限,然后才能添加標頭(它需要根據權限進行一些查找)。 由於 Spring 雲網關是反應式的,我不能使用 static SecurityContextHolder class。 引用這個 Stackoverflow 問題ReactiveSecurityContextHolder.getContext() is empty but @AuthenticationPrincipal works ,我在我的自定義 Pre 過濾器中嘗試了以下內容:

ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).block()

正如 OP 發布的那樣,它不起作用並返回 null。 有一些關於在那個 stackoverflow 問題中創建自定義過濾器的建議。 但我沒有嘗試過,因為我想從自定義過濾器訪問 Authentication object。 是否沒有直接的方法可以在 Spring 雲網關自定義過濾器中獲取 Authentication object?

謝謝

下面的代碼片段是一個簡單的過濾器示例,它提供對身份驗證上下文的訪問:

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    Mono<Void> monoFilter = ReactiveSecurityContextHolder.getContext().map(sc -> sc.getAuthentication())
            .flatMap(authentication -> {

                // here you can access to Authentication object
                // and implement the pre-filter logic

                return chain.filter(exchange);

            });

    return monoFilter;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM