#90 - Fixed port handling in X-Forwarded-Host treatment.

ControllerLinkBuilder now correctly uses the X-Fowarded-Host header by inspecting it for a port being set and configuring the discovered one on the ServletUriComponentsBuilder created.

Also added that the first host listed in the header is used.
This commit is contained in:
Frank Bille
2013-06-24 23:44:03 +02:00
committed by Oliver Gierke
parent a7baafc022
commit c5caea5efd
2 changed files with 41 additions and 2 deletions

View File

@@ -168,8 +168,23 @@ public class ControllerLinkBuilder extends LinkBuilderSupport<ControllerLinkBuil
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request);
String header = request.getHeader("X-Forwarded-Host");
if (StringUtils.hasText(header)) {
builder.host(header);
if (!StringUtils.hasText(header)) {
return builder;
}
String[] hosts = StringUtils.commaDelimitedListToStringArray(header);
String hostToUse = hosts[0];
if (hostToUse.contains(":")) {
String[] hostAndPort = StringUtils.split(hostToUse, ":");
builder.host(hostAndPort[0]);
builder.port(Integer.parseInt(hostAndPort[1]));
} else {
builder.host(hostToUse);
}
return builder;

View File

@@ -208,6 +208,30 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
assertThat(components.getQuery(), is("foo=bar"));
}
/**
* @see #90
*/
@Test
public void usesForwardedHostAndPortFromHeader() {
request.addHeader("X-Forwarded-Host", "foobar:8088");
Link link = linkTo(PersonControllerImpl.class).withSelfRel();
assertThat(link.getHref(), startsWith("http://foobar:8088"));
}
/**
* @see #90
*/
@Test
public void usesFirstHostOfXForwardedHost() {
request.addHeader("X-Forwarded-Host", "barfoo:8888, localhost:8088");
Link link = linkTo(PersonControllerImpl.class).withSelfRel();
assertThat(link.getHref(), startsWith("http://barfoo:8888"));
}
private static UriComponents toComponents(Link link) {
return UriComponentsBuilder.fromUriString(link.getHref()).build();
}