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