首页 > 解决方案 > 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 的方式根本上是错误的?

标签: springspring-webfluxspring-cloud-gateway

解决方案


通过链接到你的 Mono 然后声明你想要做什么。

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) 
{
    return exchange.getPrincipal().flatMap(principal -> {

        // Do what you need to do

        return chain.filter( ... );
    });
}

推荐阅读