Skip to content
Permalink
Browse files

Fix issue with parsing x-forwarded-host header

Issue: SPR-10701
  • Loading branch information...
rstoyanchev committed Jul 30, 2013
1 parent eec4a37 commit 6c11fd3b5e6330bf7e6820e347c407b3dc471ac6
@@ -94,9 +94,20 @@ public static ServletUriComponentsBuilder fromRequestUri(HttpServletRequest requ
public static ServletUriComponentsBuilder fromRequest(HttpServletRequest request) {
String scheme = request.getScheme();
int port = request.getServerPort();

String header = request.getHeader("X-Forwarded-Host");
String host = StringUtils.hasText(header) ? header: request.getServerName();
String host = request.getServerName();

String xForwardedHostHeader = request.getHeader("X-Forwarded-Host");

if (StringUtils.hasText(xForwardedHostHeader)) {
if (StringUtils.countOccurrencesOf(xForwardedHostHeader, ":") == 1) {
String[] hostAndPort = StringUtils.split(xForwardedHostHeader, ":");
host = hostAndPort[0];
port = Integer.parseInt(hostAndPort[1]);
}
else {
host = xForwardedHostHeader;
}
}

ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder();
builder.scheme(scheme);
@@ -16,13 +16,14 @@

package org.springframework.web.servlet.support;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UriComponents;

import static org.junit.Assert.*;

/**
* @author Rossen Stoyanchev
@@ -93,6 +94,19 @@ public void fromRequestWithForwardedHostHeader() {
assertEquals("http://anotherHost/mvc-showcase/data/param?foo=123", result);
}

// SPR-10701

@Test
public void fromRequestWithForwardedHostAndPortHeader() {
request.addHeader("X-Forwarded-Host", "webtest.foo.bar.com:443");
request.setRequestURI("/mvc-showcase/data/param");
request.setQueryString("foo=123");
UriComponents result = ServletUriComponentsBuilder.fromRequest(request).build();

assertEquals("webtest.foo.bar.com", result.getHost());
assertEquals(443, result.getPort());
}

@Test
public void fromContextPath() {
request.setRequestURI("/mvc-showcase/data/param");

0 comments on commit 6c11fd3

Please sign in to comment.
You can’t perform that action at this time.