2

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?

Yun Teng
  • 23
  • 1
  • 4

1 Answers1

2

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( ... );
    });
}
Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
  • After half of a day, finally, I find out how to work with it. But could you please explain why `exchange.getPrincipal().log().subscribe()` doesn't work? It is an empty Mono. – vahidreza Feb 08 '20 at 21:30
  • 1
    you should not subscribe in a webflux application. the subscriber is the one that initiated the call, aka. the calling client. – Toerktumlare Feb 08 '20 at 22:57