我在一个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对象的方法?
谢谢
发布于 2021-02-26 22:16:44
下面的代码片段是一个简单的筛选器示例,它提供对身份验证上下文的访问:
@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;
}https://stackoverflow.com/questions/61714699
复制相似问题