Skip to content

Commit 4160ced

Browse files
rstoyanchevjhoeller
authored andcommitted
Backport of relative redirect filter support
Issue: SPR-15717
1 parent a032e86 commit 4160ced

File tree

5 files changed

+307
-17
lines changed

5 files changed

+307
-17
lines changed

spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import javax.servlet.http.HttpServletResponseWrapper;
3232

3333
import org.springframework.http.HttpRequest;
34+
import org.springframework.http.HttpStatus;
3435
import org.springframework.http.server.ServletServerHttpRequest;
3536
import org.springframework.util.CollectionUtils;
3637
import org.springframework.util.LinkedCaseInsensitiveMap;
@@ -78,6 +79,8 @@ public class ForwardedHeaderFilter extends OncePerRequestFilter {
7879

7980
private boolean removeOnly;
8081

82+
private boolean relativeRedirects;
83+
8184

8285
public ForwardedHeaderFilter() {
8386
this.pathHelper = new UrlPathHelper();
@@ -89,13 +92,28 @@ public ForwardedHeaderFilter() {
8992
/**
9093
* Enables mode in which any "Forwarded" or "X-Forwarded-*" headers are
9194
* removed only and the information in them ignored.
92-
* @param removeOnly whether to discard and ingore forwarded headers
95+
* @param removeOnly whether to discard and ignore forwarded headers
9396
* @since 4.3.9
9497
*/
9598
public void setRemoveOnly(boolean removeOnly) {
9699
this.removeOnly = removeOnly;
97100
}
98101

102+
/**
103+
* Use this property to enable relative redirects as explained in and also
104+
* using the same response wrapper as {@link RelativeRedirectFilter} does.
105+
* Or if both filters are used, only one will wrap the response.
106+
* <p>By default, if this property is set to false, in which case calls to
107+
* {@link HttpServletResponse#sendRedirect(String)} are overridden in order
108+
* to turn relative into absolute URLs since (which Servlet containers are
109+
* also required to do) also taking forwarded headers into consideration.
110+
* @param relativeRedirects whether to use relative redirects
111+
* @since 4.3.10
112+
*/
113+
public void setRelativeRedirects(boolean relativeRedirects) {
114+
this.relativeRedirects = relativeRedirects;
115+
}
116+
99117

100118
@Override
101119
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
@@ -129,7 +147,9 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
129147
}
130148
else {
131149
HttpServletRequest theRequest = new ForwardedHeaderExtractingRequest(request, this.pathHelper);
132-
HttpServletResponse theResponse = new ForwardedHeaderExtractingResponse(response, theRequest);
150+
HttpServletResponse theResponse = (this.relativeRedirects ?
151+
RelativeRedirectResponseWrapper.wrapIfNecessary(response, HttpStatus.SEE_OTHER) :
152+
new ForwardedHeaderExtractingResponse(response, theRequest));
133153
filterChain.doFilter(theRequest, theResponse);
134154
}
135155
}
@@ -142,7 +162,6 @@ private static class ForwardedHeaderRemovingRequest extends HttpServletRequestWr
142162

143163
private final Map<String, List<String>> headers;
144164

145-
146165
public ForwardedHeaderRemovingRequest(HttpServletRequest request) {
147166
super(request);
148167
this.headers = initHeaders(request);
@@ -180,6 +199,7 @@ public Enumeration<String> getHeaderNames() {
180199
}
181200
}
182201

202+
183203
/**
184204
* Extract and use "Forwarded" or "X-Forwarded-*" headers.
185205
*/
@@ -199,7 +219,6 @@ private static class ForwardedHeaderExtractingRequest extends ForwardedHeaderRem
199219

200220
private final String requestUrl;
201221

202-
203222
public ForwardedHeaderExtractingRequest(HttpServletRequest request, UrlPathHelper pathHelper) {
204223
super(request);
205224

@@ -276,10 +295,8 @@ private static class ForwardedHeaderExtractingResponse extends HttpServletRespon
276295

277296
private static final String FOLDER_SEPARATOR = "/";
278297

279-
280298
private final HttpServletRequest request;
281299

282-
283300
public ForwardedHeaderExtractingResponse(HttpServletResponse response, HttpServletRequest request) {
284301
super(response);
285302
this.request = request;
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* Copyright 2002-2017 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.web.filter;
18+
19+
import java.io.IOException;
20+
import javax.servlet.FilterChain;
21+
import javax.servlet.ServletException;
22+
import javax.servlet.http.HttpServletRequest;
23+
import javax.servlet.http.HttpServletResponse;
24+
25+
import org.springframework.http.HttpStatus;
26+
import org.springframework.util.Assert;
27+
28+
/**
29+
* Overrides {@link HttpServletResponse#sendRedirect(String)} and handles it by
30+
* setting the HTTP status and "Location" headers. This keeps the Servlet
31+
* container from re-writing relative redirect URLs and instead follows the
32+
* recommendation in <a href="https://tools.ietf.org/html/rfc7231#section-7.1.2">
33+
* RFC 7231 Section 7.1.2</a>.
34+
*
35+
* <p><strong>Note:</strong> While relative redirects are more efficient they
36+
* may not work with reverse proxies under some configurations.
37+
*
38+
* @author Rob Winch
39+
* @author Rossen Stoyanchev
40+
* @since 4.3.10
41+
*/
42+
public class RelativeRedirectFilter extends OncePerRequestFilter {
43+
44+
private HttpStatus redirectStatus = HttpStatus.SEE_OTHER;
45+
46+
47+
/**
48+
* Set the default HTTP Status to use for redirects.
49+
* <p>By default this is {@link HttpStatus#SEE_OTHER}.
50+
* @param status the 3xx redirect status to use
51+
*/
52+
public void setRedirectStatus(HttpStatus status) {
53+
Assert.notNull(status, "Property 'redirectStatus' is required");
54+
Assert.isTrue(status.is3xxRedirection(), "Not a redirect status code");
55+
this.redirectStatus = status;
56+
}
57+
58+
/**
59+
* Return the configured redirect status.
60+
*/
61+
public HttpStatus getRedirectStatus() {
62+
return this.redirectStatus;
63+
}
64+
65+
66+
@Override
67+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
68+
FilterChain filterChain) throws ServletException, IOException {
69+
70+
response = RelativeRedirectResponseWrapper.wrapIfNecessary(response, this.redirectStatus);
71+
filterChain.doFilter(request, response);
72+
}
73+
74+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Copyright 2002-2017 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.web.filter;
17+
18+
import java.io.IOException;
19+
import javax.servlet.ServletResponse;
20+
import javax.servlet.http.HttpServletResponse;
21+
import javax.servlet.http.HttpServletResponseWrapper;
22+
23+
import org.springframework.http.HttpHeaders;
24+
import org.springframework.http.HttpStatus;
25+
import org.springframework.util.Assert;
26+
27+
/**
28+
* A response wrapper used for the implementation of
29+
* {@link RelativeRedirectFilter} also shared with {@link ForwardedHeaderFilter}.
30+
*
31+
* @author Rossen Stoyanchev
32+
* @since 4.3.10
33+
*/
34+
class RelativeRedirectResponseWrapper extends HttpServletResponseWrapper {
35+
36+
private final HttpStatus redirectStatus;
37+
38+
39+
private RelativeRedirectResponseWrapper(HttpServletResponse response, HttpStatus redirectStatus) {
40+
super(response);
41+
Assert.notNull(redirectStatus, "'redirectStatus' is required");
42+
this.redirectStatus = redirectStatus;
43+
}
44+
45+
46+
@Override
47+
public void sendRedirect(String location) throws IOException {
48+
setStatus(this.redirectStatus.value());
49+
setHeader(HttpHeaders.LOCATION, location);
50+
}
51+
52+
53+
public static HttpServletResponse wrapIfNecessary(HttpServletResponse response,
54+
HttpStatus redirectStatus) {
55+
56+
return (hasWrapper(response) ? response : new RelativeRedirectResponseWrapper(response, redirectStatus));
57+
}
58+
59+
private static boolean hasWrapper(ServletResponse response) {
60+
if (response instanceof RelativeRedirectResponseWrapper) {
61+
return true;
62+
}
63+
while (response instanceof HttpServletResponseWrapper) {
64+
response = ((HttpServletResponseWrapper) response).getResponse();
65+
if (response instanceof RelativeRedirectResponseWrapper) {
66+
return true;
67+
}
68+
}
69+
return false;
70+
}
71+
72+
}

spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2016 the original author or authors.
2+
* Copyright 2002-2017 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -13,11 +13,11 @@
1313
* See the License for the specific language governing permissions and
1414
* limitations under the License.
1515
*/
16+
1617
package org.springframework.web.filter;
1718

1819
import java.io.IOException;
1920
import java.util.Enumeration;
20-
2121
import javax.servlet.Filter;
2222
import javax.servlet.FilterChain;
2323
import javax.servlet.ServletException;
@@ -32,20 +32,18 @@
3232
import org.springframework.mock.web.test.MockHttpServletRequest;
3333
import org.springframework.mock.web.test.MockHttpServletResponse;
3434

35-
import static org.junit.Assert.assertEquals;
36-
import static org.junit.Assert.assertFalse;
37-
import static org.junit.Assert.assertNull;
38-
import static org.junit.Assert.assertTrue;
35+
import static org.junit.Assert.*;
3936

4037
/**
4138
* Unit tests for {@link ForwardedHeaderFilter}.
39+
*
4240
* @author Rossen Stoyanchev
4341
* @author Eddú Meléndez
4442
* @author Rob Winch
4543
*/
4644
public class ForwardedHeaderFilterTests {
4745

48-
private static final String X_FORWARDED_PROTO = "x-forwarded-proto"; // SPR-14372 (case insensitive)
46+
private static final String X_FORWARDED_PROTO = "x-forwarded-proto"; // SPR-14372 (case insensitive)
4947
private static final String X_FORWARDED_HOST = "x-forwarded-host";
5048
private static final String X_FORWARDED_PORT = "x-forwarded-port";
5149
private static final String X_FORWARDED_PREFIX = "x-forwarded-prefix";
@@ -60,7 +58,7 @@ public class ForwardedHeaderFilterTests {
6058

6159
@Before
6260
@SuppressWarnings("serial")
63-
public void setUp() throws Exception {
61+
public void setup() throws Exception {
6462
this.request = new MockHttpServletRequest();
6563
this.request.setScheme("http");
6664
this.request.setServerName("localhost");
@@ -185,9 +183,7 @@ public void requestUriPreserveSemicolonContent() throws Exception {
185183
@Test
186184
public void caseInsensitiveForwardedPrefix() throws Exception {
187185
this.request = new MockHttpServletRequest() {
188-
189186
// Make it case-sensitive (SPR-14372)
190-
191187
@Override
192188
public String getHeader(String header) {
193189
Enumeration<String> names = getHeaderNames();
@@ -404,6 +400,27 @@ public void sendRedirectWithNoXForwardedAndDotDotPath() throws Exception {
404400
assertEquals("../foo/bar", redirectedUrl);
405401
}
406402

403+
@Test
404+
public void sendRedirectWhenRequestOnlyAndXForwardedThenUsesRelativeRedirects() throws Exception {
405+
this.request.addHeader(X_FORWARDED_PROTO, "https");
406+
this.request.addHeader(X_FORWARDED_HOST, "example.com");
407+
this.request.addHeader(X_FORWARDED_PORT, "443");
408+
this.filter.setRelativeRedirects(true);
409+
410+
String location = sendRedirect("/a");
411+
412+
assertEquals("/a", location);
413+
}
414+
415+
@Test
416+
public void sendRedirectWhenRequestOnlyAndNoXForwardedThenUsesRelativeRedirects() throws Exception {
417+
this.filter.setRelativeRedirects(true);
418+
419+
String location = sendRedirect("/a");
420+
421+
assertEquals("/a", location);
422+
}
423+
407424
private String sendRedirect(final String location) throws ServletException, IOException {
408425
MockHttpServletResponse response = doWithFiltersAndGetResponse(this.filter, new OncePerRequestFilter() {
409426
@Override
@@ -412,10 +429,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
412429
response.sendRedirect(location);
413430
}
414431
});
415-
416432
return response.getRedirectedUrl();
417433
}
418434

435+
@SuppressWarnings("serial")
419436
private MockHttpServletResponse doWithFiltersAndGetResponse(Filter... filters) throws ServletException, IOException {
420437
MockHttpServletResponse response = new MockHttpServletResponse();
421438
FilterChain filterChain = new MockFilterChain(new HttpServlet() {}, filters);

0 commit comments

Comments
 (0)