我需要添加一些来自exchange.getPrincipal()
转发请求的用户信息,并写GlobalFilter
如下:
public class UserInfoFilter implements GlobalFilter, Ordered {
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest.Builder mutate = exchange.getRequest().mutate();
return exchange.getPrincipal().map(principal -> {
if (principal instanceof Authentication) {
Authentication authentication = (Authentication) principal;
Object principal1 = authentication.getPrincipal();
if (principal1 instanceof UserDetails) {
UserDetails user = (UserDetails) principal1;
mutate.header("userName", user.getUsername());
}
}
return mutate;
}).doOnSuccess(builder -> chain.filter(exchange.mutate().request(builder.build()).build())).then();
}
}
但是当我启用这个过滤器时,我只会得到一个 200 状态码而没有任何异常抛出。我想我使用了错误的反应器方式,我尝试了很多但无法让它工作。