Yun Teng
Yun Teng

Reputation: 33

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

I am currently doing Spring Cloud Gateway using custom JWT authentication. After authentication I want to pass the JWT token string in the header into downstream service using a GlobalFilter:

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;
    }
}

The JWT token string can be obtained by calling Principal.getName();

My question is: how can I implement the String extract(Mono<Principal> principal) method in order to convert the Mono to JWT token string when add the token string as a header? Or my way of using Mono is fundamentally wrong?

Upvotes: 3

Views: 2185

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14712

By chaining onto your Mono and then declare what you want to do.

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

        // Do what you need to do

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

Upvotes: 2

Related Questions