Spring boot 在Spring云网关预过滤器中获取SecurityContextHolder
我正在SpringBoot项目(版本2.2.6)中使用SpringCloudGateway和SpringSecurity。我有一个定制的预过滤器,它需要在将请求转发到下游服务之前向请求添加头。预过滤器需要读取Spring Security的身份验证对象以获取权限,然后才能添加头(它需要根据权限进行一些查找)。因为SpringCloudGateway是被动的,所以我不能使用静态SecurityContextHolder类。参考此Stackoverflow问题,我在自定义预过滤器中尝试了以下操作:Spring boot 在Spring云网关预过滤器中获取SecurityContextHolder,spring-boot,spring-security,spring-cloud-gateway,Spring Boot,Spring Security,Spring Cloud Gateway,我正在SpringBoot项目(版本2.2.6)中使用SpringCloudGateway和SpringSecurity。我有一个定制的预过滤器,它需要在将请求转发到下游服务之前向请求添加头。预过滤器需要读取Spring Security的身份验证对象以获取权限,然后才能添加头(它需要根据权限进行一些查找)。因为SpringCloudGateway是被动的,所以我不能使用静态SecurityContextHolder类。参考此Stackoverflow问题,我在自定义预过滤器中尝试了以下操作:
ReactiveSecurityContextHolder.getContext().map(ctx->ctx.getAuthentication()).block()
当OP发布时,它不工作并且返回null。有一些关于在stackoverflow问题中创建自定义筛选器的建议。但我没有尝试过,因为我想从自定义筛选器访问身份验证对象。在SpringCloudGateway自定义过滤器中是否没有直接的方法来获取身份验证对象
谢谢下面的代码片段是一个简单的过滤器示例,它提供对身份验证上下文的访问:
@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;
}
@覆盖
公共Mono筛选器(服务器WebExchange exchange、网关筛选器链){
Mono monoFilter=ReactiveSecurityContextHolder.getContext().map(sc->sc.getAuthentication())
.flatMap(身份验证->{
//在这里,您可以访问身份验证对象
//并实现了预滤波逻辑
返回链。过滤器(交换);
});
返回单滤器;
}
下面的代码片段是一个简单的过滤器示例,它提供对身份验证上下文的访问:
@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;
}
@覆盖
公共Mono筛选器(服务器WebExchange exchange、网关筛选器链){
Mono monoFilter=ReactiveSecurityContextHolder.getContext().map(sc->sc.getAuthentication())
.flatMap(身份验证->{
//在这里,您可以访问身份验证对象
//并实现了预滤波逻辑
返回链。过滤器(交换);
});
返回单滤器;
}