spring - Spring Webflux & Spring Cloud Gateway:如何在 Mono 中提取对象并添加到请求标头
问题描述
我目前正在使用自定义 JWT 身份验证执行 Spring Cloud Gateway。身份验证后,我想使用 GlobalFilter 将标头中的 JWT 令牌字符串传递给下游服务:
public class AddJwtHeaderGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Mono<Principal> principal = exchange.getPrincipal();
String jwtString = extract(principal);
ServerHttpRequest request = exchange.getRequest()
.mutate()
.header("Authorization", new String[]{jwtString})
.build();
ServerWebExchange newExchange = exchange.mutate().request(request).build();
return chain.filter(newExchange);
}
// how to implement this method in order to get a String type of jwt token?
private String extract(Mono<Principal> principal) {
//need to call getJwtString(Principal) and return the jwt string
return null;
}
private String getJwtString(Principal principal) {
return principal.getName();
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
调用 Principal.getName() 可以获取 JWT 令牌字符串;
我的问题是:当将令牌字符串添加为标头时,如何实现该String extract(Mono<Principal> principal)
方法以将 Mono 转换为 JWT 令牌字符串?还是我使用 Mono 的方式根本上是错误的?
解决方案
通过链接到你的 Mono 然后声明你想要做什么。
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
{
return exchange.getPrincipal().flatMap(principal -> {
// Do what you need to do
return chain.filter( ... );
});
}
推荐阅读
- php - 未找到列:1054 未知列 'token' 如果我放置了令牌
- android - 反编译 React Native index.android.bundle
- xamarin.forms - PanGestureRecognizer 在拖动过程中零星出现
- javascript - JavaScript 函数动态调用 className
- encoding - 这个文本是什么类型的编码?
- javascript - ReactTable - 基于单个列中的多个值进行过滤
- javascript - 如何实现在滚动上替换前一个的复杂粘性部分标题?
- installation - 我可以在 Inno Setup 的同一个“CreateInputOptionPage”页面上有复选框和单选按钮吗?
- javascript - 同时与多个选项卡通信的 Chrome 扩展程序
- python - 使用字典替换字符串不起作用