简体   繁体   English

在 Spring 云网关前置过滤器中获取 SecurityContextHolder

[英]Getting SecurityContextHolder in Spring Cloud Gateway Pre Filter

I am using Spring Cloud Gateway and Spring Security in a Spring Boot project (version 2.2.6).我在 Spring 引导项目(版本 2.2.6)中使用 Spring 云网关和 Spring 安全性。 I have a custom Pre filter which needs to add headers to the request before it forwards the request to the downstream services.我有一个自定义的 Pre 过滤器,它需要在将请求转发到下游服务之前向请求添加标头。 The Pre filter needs to read Spring Security's Authentication object to get the authorities before it can add the headers (it needs to do some lookup based on the authorities). Pre 过滤器需要读取 Spring Security's Authentication object 以获取权限,然后才能添加标头(它需要根据权限进行一些查找)。 Since Spring Cloud Gateway is reactive, I cannot use the static SecurityContextHolder class.由于 Spring 云网关是反应式的,我不能使用 static SecurityContextHolder class。 Referencing this Stackoverflow question ReactiveSecurityContextHolder.getContext() is empty but @AuthenticationPrincipal works , I tried the following in my custom Pre filter:引用这个 Stackoverflow 问题ReactiveSecurityContextHolder.getContext() is empty but @AuthenticationPrincipal works ,我在我的自定义 Pre 过滤器中尝试了以下内容:

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

As the OP posted, it does not work and it returns null.正如 OP 发布的那样,它不起作用并返回 null。 There were some suggestions about creating a custom filter in that stackoverflow issue.有一些关于在那个 stackoverflow 问题中创建自定义过滤器的建议。 But I have not tried it as I want to access the Authentication object from the custom filter.但我没有尝试过,因为我想从自定义过滤器访问 Authentication object。 Is there no direct way to get the Authentication object in the Spring Cloud Gateway custom filter?是否没有直接的方法可以在 Spring 云网关自定义过滤器中获取 Authentication object?

Thanks谢谢

The code snippet below is a simple example of a filter which provides access to the Authentication context:下面的代码片段是一个简单的过滤器示例,它提供对身份验证上下文的访问:

@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