Spring Webflux & Spring Cloud Gateway:如何在 Mono 中提取 object 并添加到请求 header
Spring Webflux & Spring Cloud Gateway: how to extract object in Mono and add to request header
我目前正在 Spring 使用自定义 JWT 身份验证的云网关。身份验证后,我想使用 GlobalFilter:
将 header 中的 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 token字符串
我的问题是:当将令牌字符串添加为 header 时,如何实现 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( ... );
});
}
我目前正在 Spring 使用自定义 JWT 身份验证的云网关。身份验证后,我想使用 GlobalFilter:
将 header 中的 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 token字符串我的问题是:当将令牌字符串添加为 header 时,如何实现 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( ... );
});
}