0

I have a request/route that should be redirected to another server. For this, I thought using a redirect filter from 'spring-cloud-gateway' should be the right thing. Example: http://localhost:8080/site/rest/services/testservice/1 should be redirected to https://internal-api.com/site/rest/services/testservice/1.

So far I came up with the following filters in a RouteLocator:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    String auth = username + ":" + password;
    String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
    
    return builder.routes()
            .route("geoApi", r -> r
                    .path("/site/rest/services/**")
                    .filters(f -> {
                        f.setRequestHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);
                        f.redirect(302, "https://internal-api.com");
                        return f;
                    })
                    .uri("https://internal-api.com"))
            .build();
}

The redirect works, but only goes to the "root" url of the internal API and not the "/site/rest/...". How can I fix this?

sandrooco
  • 8,016
  • 9
  • 48
  • 86
  • See the rewrite location header filter https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the-rewritelocationresponseheader-gatewayfilter-factory – spencergibb Jan 25 '23 at 15:41
  • @spencergibb is my usecase actually the intended use for this feature? – sandrooco Jan 27 '23 at 07:10

2 Answers2

0

This is how I achieved to correctly redirect it. I'm not sure if this is the cleanest solution though. I couldn't get spencergibb's input to work...

f.changeRequestUri(e -> {
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(e.getRequest().getURI());
    String modifiedUri = uriBuilder.scheme("https").host("internal-api.com").port(null).toUriString();
    return Optional.of(URI.create(modifiedUri));
});
sandrooco
  • 8,016
  • 9
  • 48
  • 86
0

You need to use rewrite path filter:

return builder.routes()
        .route("geoApi", r -> r
                .path("/site/rest/services/**")
                .filters(f -> f.rewritePath("/site/rest/services/(?<segment>.*)", "/site/rest/services/${segment}"))
                .uri("https://internal-api.com"))
        .build();

This is answered under this Stack Overflow question.

denu
  • 2,170
  • 2
  • 23
  • 28