首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Spring Cloud Gateway预过滤中获取SecurityContextHolder

在Spring Cloud Gateway预过滤中获取SecurityContextHolder
EN

Stack Overflow用户
提问于 2020-05-10 23:47:53
回答 1查看 505关注 0票数 1

我在一个Spring Boot项目(2.2.6版)中使用了Spring Cloud Gateway和Spring Security。我有一个自定义的预过滤器,它需要在将请求转发到下游服务之前向请求添加标头。预过滤器需要读取Spring Security的Authentication对象来获取权限,然后才能添加头部(它需要根据权限进行一些查找)。由于Spring Cloud Gateway是响应式的,所以我不能使用静态SecurityContextHolder类。参考这个堆栈溢出问题ReactiveSecurityContextHolder.getContext() is empty but @AuthenticationPrincipal works,我在我的自定义预过滤器中尝试了以下内容:

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

正如OP发布的那样,它不工作并且返回null。在这个堆栈溢出问题中,有一些关于创建自定义过滤器的建议。但我没有尝试过,因为我想从自定义筛选器访问Authentication对象。在Spring Cloud Gateway自定义筛选器中是否没有直接获取Authentication对象的方法?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-02-26 22:16:44

下面的代码片段是一个简单的筛选器示例,它提供对身份验证上下文的访问:

代码语言:javascript
复制
@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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61714699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档