spring-cloud-gateway icon indicating copy to clipboard operation
spring-cloud-gateway copied to clipboard

How to call another micro-service on GatewayFilterFactory ?

Open unsciorg opened this issue 7 years ago • 14 comments

Hello, Can you tell me how to call another micro-service on a GatewayFilterFactory?

I want to call the authentication micro-service when a request come from user. 1st, I tried to use feign client. but I can not get the ServletRequestAttribute on the RequestInterceptor because spring cloud gateway use webflux instead of web. Here is the code :

public class FeignAuthRequestInterceptor implements RequestInterceptor {

    private final Logger logger = LoggerFactory.getLogger(FeignAuthRequestInterceptor.class);
    private static final String HEADER_TOKEN = "token";
    private static final String HEADER_USERNAME = "username";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//TODO the attribute is always null so I can not get the original request header
        logger.warn("the request attribute is {}", attributes);
        Map<String, Collection<String>> queries = requestTemplate.queries();
        if (requestTemplate.queries().get(HEADER_TOKEN) != null) {
            requestTemplate.header(HEADER_TOKEN, queries.get(HEADER_TOKEN).iterator().next());
        }
        if (requestTemplate.queries().get(HEADER_USERNAME) != null) {
            requestTemplate.header(HEADER_USERNAME, queries.get(HEADER_USERNAME).iterator().next());
        }
        requestTemplate.queries(queries);
        /**
         HttpServletRequest request = attributes.getRequest();
         Enumeration<String> headerNames = request.getHeaderNames();
         if (headerNames != null) {
         while (headerNames.hasMoreElements()) {
         String name = headerNames.nextElement();
         String values = request.getHeader(name);
         requestTemplate.header(name, values);
         }
         }
         **/
    }
}

Then I tried to use webClient of spring5 to make a request to the authentication micro-service but I can not get the response

Mono<ResponseResult> res = webClient.post().uri(auth.getAuthUri())
                    .headers((httpHeaders -> httpHeaders.putAll(exchange.getRequest().getHeaders())))
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(BodyInserters.fromObject(JSONObject.toJSONString(params)))
                    .accept(MediaType.APPLICATION_JSON_UTF8)
                    .retrieve()
//                    .bodyToMono(ResponseResult.class);
                    .bodyToMono(ResponseResult.class)
                    ;

When I use the

res.block();

method to get the response , there is an exception

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2"

So. I want to know how to call another micro-service on spring cloud gateway environment. Thanks a lot. best wishes.

unsciorg avatar Jun 01 '19 06:06 unsciorg

Feign is not going to work as it is not reactive.

This is also why you cannot call .block.

Unfortunately it is hard to say what is wrong without a way to reproduce the problem. Using WebClient should be fine.

ryanjbaxter avatar Jun 04 '19 00:06 ryanjbaxter

Feign is not going to work as it is not reactive.

This is also why you cannot call .block.

Unfortunately it is hard to say what is wrong without a way to reproduce the problem. Using WebClient should be fine.

I tried to use WebClient ,But I do not know how to get the response from webclient call. Usually, .block() works. But it does not work well in webflux environment. So would you mind tell me how to get the response when using WebClient ? Thanks a lot .

Best wishes to you . @ryanjbaxter

unsciorg avatar Jun 04 '19 00:06 unsciorg

See https://github.com/spring-cloud/spring-cloud-security/blob/master/spring-cloud-security/src/main/java/org/springframework/cloud/security/oauth2/gateway/TokenRelayGatewayFilterFactory.java

For an example

spencergibb avatar Jun 04 '19 00:06 spencergibb

Thanks a lot. I take a cursory look. But I am sorry, I don't think that's what I need. I deployed an authentication service used shiro in another project. So I need a way to call that. I want to use WebClient as @ryanjbaxter said . But I can not get the webclient response without .block method . Sorry for the inconvenience.

unsciorg avatar Jun 04 '19 01:06 unsciorg

Take more than a cursory look. The class in the filter could be replaced with webclient. In fact I think if you dig into it, it uses web client.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-webclient.html

spencergibb avatar Jun 04 '19 01:06 spencergibb

Thanks . And Thank you for your contribution to spring cloud development.

unsciorg avatar Jun 04 '19 01:06 unsciorg

hello spencergibb, I can not find the source code about the ServerOAuth2AuthorizedClientRepository class.

unsciorg avatar Jun 04 '19 03:06 unsciorg

https://github.com/spring-projects/spring-security/blob/master/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizedClientRepository.java

But it doesn't really matter. This issue isn't to provide a lesson on reactive programming with reactor.

spencergibb avatar Jun 04 '19 18:06 spencergibb

See https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/WebClientHttpRoutingFilter.java

And

https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/WebClientWriteResponseFilter.java

spencergibb avatar Jun 05 '19 04:06 spencergibb

@vxray
I have the same problem as you

@Override
public GatewayFilter apply(Config config) {
    return ((exchange, chain) -> {
        WebClient.create().post().uri("http://127.0.0.1:9001/user/query").retrieve().bodyToMono
                (String.class).flatMap(s -> {
            System.out.println(s);
            return Mono.just(s);
        });
        return chain.filter(exchange);
    });

how to get WebClient response

qiufuzong avatar Jun 07 '19 18:06 qiufuzong

the webclient all returns a Mono and needs to be part of the filter chain. So instead of return Mono.just(s).

@Override
public GatewayFilter apply(Config config) {
    return ((exchange, chain) -> {
        return WebClient.create().post().uri("http://127.0.0.1:9001/user/query").retrieve().bodyToMono
                (String.class).flatMap(s -> {
            System.out.println(s);
            return chain.filter(exchange);
        });
    });

spencergibb avatar Jun 07 '19 18:06 spencergibb

@spencergibb

the webclient all returns a Mono and needs to be part of the filter chain. So instead of return Mono.just(s).

@Override
public GatewayFilter apply(Config config) {
    return ((exchange, chain) -> {
        return WebClient.create().post().uri("http://127.0.0.1:9001/user/query").retrieve().bodyToMono
                (String.class).flatMap(s -> {
            System.out.println(s);
            return chain.filter(exchange);
        });
    });

Can I pass service name in URI, because port will be dynamic

khairali-sysltd avatar Apr 13 '23 23:04 khairali-sysltd

I also had the same kind of problem and got resolved as mentioned in this answer https://stackoverflow.com/a/77624403/1057291

You can check the demo project here https://github.com/namalfernandolk/cloud-gateway-demo.git

namalfernandolk avatar Dec 08 '23 20:12 namalfernandolk

@namalfernandolk Is webClient need set timeout or not ? code: webClient.post() .uri(uri) .contentType(MediaType.APPLICATION_JSON) .bodyValue(vo) .retrieve() .bodyToMono(String.class) .timeout(Duration.ofSeconds(5))

monkeyk avatar Feb 05 '24 06:02 monkeyk