Spring Webflux 和 Spring Cloud Gateway : how to extract object in Mono and add to request header

标签 spring spring-webflux spring-cloud-gateway

我目前正在使用自定义 JWT 身份验证进行 Spring Cloud Gateway。身份验证后,我想使用 GlobalFilter 将 header 中的 JWT token 字符串传递到下游服务:

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字符串;

我的问题是:如何实现 String extract(Mono<Principal> principal)将 token 字符串添加为 header 时将 Mono 转换为 JWT token 字符串的方法?或者我使用 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 Webflux 和 Spring Cloud Gateway : how to extract object in Mono and add to request header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008565/

相关文章:

spring - 在一段时间内从 channel 消耗给定数量的消息

java - 使用cascade={CascadeType.TYPE_NAME}的目的是什么

java - 使用数据库@Entity 类进行 REST 公开?

java - 如何在不阻塞的情况下从 Flux 获取 List?

java - 在 Spring Boot Webflux 中生成服务器发送的事件

java - Spring Cloud Gateway 不适用于 @Bean DiscoveryClientRouteDefinitionLocator

java - Spring 项目如何访问 JBoss JNDI 数据源

java - 在 RestController 方法中获取 ServerWebExchange

java - Spring Cloud Gateway 未找到路由路径(404 错误)

spring-cloud - 如何在Spring Cloud Gateway中为每个路由设置超时?