Skip to content

Commit 68e6b14

Browse files
committed
Refactor relative redirect filter support
Issue: SPR-15717
1 parent fadf04e commit 68e6b14

File tree

5 files changed

+162
-70
lines changed

5 files changed

+162
-70
lines changed

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

Lines changed: 16 additions & 14 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.lang.Nullable;
3637
import org.springframework.util.CollectionUtils;
@@ -79,7 +80,7 @@ public class ForwardedHeaderFilter extends OncePerRequestFilter {
7980

8081
private boolean removeOnly;
8182

82-
private boolean requestOnly;
83+
private boolean relativeRedirects;
8384

8485

8586
public ForwardedHeaderFilter() {
@@ -100,21 +101,21 @@ public void setRemoveOnly(boolean removeOnly) {
100101
}
101102

102103
/**
103-
* Enables mode in which only the HttpServletRequest is modified. This means that
104-
* {@link HttpServletResponse#sendRedirect(String)} will only work when the application is configured to use
105-
* relative redirects. This can be done by placing {@link RelativeRedirectFilter} after this Filter or Servlet
106-
* Container specific setup. For example, using Tomcat's
107-
* <a href="https://tomcat.apache.org/tomcat-8.0-doc/config/context.html#Common_Attributes">useRelativeRedirects</a>
108-
* attribute.
109-
*
110-
* @param requestOnly whether to customize the {@code HttpServletResponse} or not. Default is false (customize the
111-
* {@code HttpServletResponse})
112-
* @since 4.3.10
104+
* Use this property to enable relative redirects as explained in and also
105+
* using the same response wrapper as {@link RelativeRedirectFilter} does.
106+
* Or if both filters are used, only one will wrap the response.
107+
* <p>By default, if this property is set to false, in which case calls to
108+
* {@link HttpServletResponse#sendRedirect(String)} are overridden in order
109+
* to turn relative into absolute URLs since (which Servlet containers are
110+
* also required to do) also taking forwarded headers into consideration.
111+
* @param relativeRedirects whether to use relative redirects
112+
* @since 5.0
113113
*/
114-
public void setRequestOnly(boolean requestOnly) {
115-
this.requestOnly = requestOnly;
114+
public void setRelativeRedirects(boolean relativeRedirects) {
115+
this.relativeRedirects = relativeRedirects;
116116
}
117117

118+
118119
@Override
119120
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
120121
Enumeration<String> names = request.getHeaderNames();
@@ -147,7 +148,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
147148
}
148149
else {
149150
HttpServletRequest theRequest = new ForwardedHeaderExtractingRequest(request, this.pathHelper);
150-
HttpServletResponse theResponse = this.requestOnly ? response :
151+
HttpServletResponse theResponse = this.relativeRedirects ?
152+
RelativeRedirectResponseWrapper.wrapIfNecessary(response, HttpStatus.SEE_OTHER) :
151153
new ForwardedHeaderExtractingResponse(response, theRequest);
152154
filterChain.doFilter(theRequest, theResponse);
153155
}

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

Lines changed: 31 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -16,71 +16,59 @@
1616

1717
package org.springframework.web.filter;
1818

19-
import org.springframework.http.HttpHeaders;
2019
import org.springframework.http.HttpStatus;
2120
import org.springframework.util.Assert;
2221

2322
import javax.servlet.FilterChain;
2423
import javax.servlet.ServletException;
2524
import javax.servlet.http.HttpServletRequest;
2625
import javax.servlet.http.HttpServletResponse;
27-
import javax.servlet.http.HttpServletResponseWrapper;
2826
import java.io.IOException;
2927

3028
/**
31-
* Overrides the {@link HttpServletResponse#sendRedirect(String)} to set the "Location" header and the HTTP Status
32-
* directly to avoid the Servlet Container from creating an absolute URL. This allows redirects that have a relative
33-
* "Location" that ensures support for <a href="https://tools.ietf.org/html/rfc7231#section-7.1.2">RFC 7231 Section
34-
* 7.1.2</a>. It should be noted that while relative redirects are more efficient, they may not work with reverse
35-
* proxies under some configurations.
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.
3637
*
3738
* @author Rob Winch
38-
* @since 4.3.10
39+
* @author Rossen Stoyanchev
40+
* @since 5.0
3941
*/
4042
public class RelativeRedirectFilter extends OncePerRequestFilter {
41-
private HttpStatus sendRedirectHttpStatus = HttpStatus.FOUND;
43+
44+
private HttpStatus redirectStatus = HttpStatus.SEE_OTHER;
45+
4246

4347
/**
44-
* Sets the HTTP Status to be used when {@code HttpServletResponse#sendRedirect(String)} is invoked.
45-
* @param sendRedirectHttpStatus the 3xx HTTP Status to be used when
46-
* {@code HttpServletResponse#sendRedirect(String)} is invoked. The default is {@code HttpStatus.FOUND}.
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
4751
*/
48-
public void setSendRedirectHttpStatus(HttpStatus sendRedirectHttpStatus) {
49-
Assert.notNull(sendRedirectHttpStatus, "HttpStatus is required");
50-
if(!sendRedirectHttpStatus.is3xxRedirection()) {
51-
throw new IllegalArgumentException("sendRedirectHttpStatus should be for redirection. Got " + sendRedirectHttpStatus);
52-
}
53-
this.sendRedirectHttpStatus = sendRedirectHttpStatus;
54-
}
55-
56-
@Override
57-
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
58-
filterChain.doFilter(request, new RelativeRedirectResponse(response));
52+
public void setRedirectStatus(HttpStatus status) {
53+
Assert.notNull(status, "HttpStatus is required");
54+
Assert.isTrue(status.is3xxRedirection(), "Not a redirect status: " + status);
55+
this.redirectStatus = status;
5956
}
6057

6158
/**
62-
* Modifies {@link #sendRedirect(String)} to explicitly set the "Location" header and an HTTP status code to avoid
63-
* containers from rewriting the location to be an absolute URL.
64-
*
65-
* @author Rob Winch
66-
* @since 4.3.10
59+
* Return the configured redirect status.
6760
*/
68-
private class RelativeRedirectResponse extends HttpServletResponseWrapper {
61+
public HttpStatus getRedirectStatus() {
62+
return this.redirectStatus;
63+
}
6964

70-
/**
71-
* Constructs a response adaptor wrapping the given response.
72-
*
73-
* @param response
74-
* @throws IllegalArgumentException if the response is null
75-
*/
76-
public RelativeRedirectResponse(HttpServletResponse response) {
77-
super(response);
78-
}
7965

80-
@Override
81-
public void sendRedirect(String location) throws IOException {
82-
setHeader(HttpHeaders.LOCATION, location);
83-
setStatus(sendRedirectHttpStatus.value());
84-
}
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);
8572
}
73+
8674
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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 5.0
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 :
57+
new RelativeRedirectResponseWrapper(response, redirectStatus);
58+
}
59+
60+
private static boolean hasWrapper(ServletResponse response) {
61+
if (response instanceof RelativeRedirectResponseWrapper) {
62+
return true;
63+
}
64+
while (response instanceof HttpServletResponseWrapper) {
65+
response = ((HttpServletResponseWrapper) response).getResponse();
66+
if (response instanceof RelativeRedirectResponseWrapper) {
67+
return true;
68+
}
69+
}
70+
return false;
71+
}
72+
73+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,7 @@ public void sendRedirectWhenRequestOnlyAndXForwardedThenUsesRelativeRedirects()
408408
this.request.addHeader(X_FORWARDED_PROTO, "https");
409409
this.request.addHeader(X_FORWARDED_HOST, "example.com");
410410
this.request.addHeader(X_FORWARDED_PORT, "443");
411-
this.filter.setRequestOnly(true);
411+
this.filter.setRelativeRedirects(true);
412412

413413
String location = sendRedirect("/a");
414414

@@ -417,7 +417,7 @@ public void sendRedirectWhenRequestOnlyAndXForwardedThenUsesRelativeRedirects()
417417

418418
@Test
419419
public void sendRedirectWhenRequestOnlyAndNoXForwardedThenUsesRelativeRedirects() throws Exception {
420-
this.filter.setRequestOnly(true);
420+
this.filter.setRelativeRedirects(true);
421421

422422
String location = sendRedirect("/a");
423423

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

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,67 +16,96 @@
1616

1717
package org.springframework.web.filter;
1818

19+
import javax.servlet.http.HttpServletResponse;
20+
import javax.servlet.http.HttpServletResponseWrapper;
21+
1922
import org.junit.Test;
2023
import org.junit.runner.RunWith;
2124
import org.mockito.InOrder;
2225
import org.mockito.Mock;
2326
import org.mockito.Mockito;
2427
import org.mockito.junit.MockitoJUnitRunner;
28+
2529
import org.springframework.http.HttpHeaders;
2630
import org.springframework.http.HttpStatus;
2731
import org.springframework.mock.web.test.MockFilterChain;
2832
import org.springframework.mock.web.test.MockHttpServletRequest;
33+
import org.springframework.mock.web.test.MockHttpServletResponse;
2934

30-
import javax.servlet.http.HttpServletResponse;
35+
import static org.junit.Assert.assertNotSame;
36+
import static org.junit.Assert.assertSame;
3137

3238
/**
39+
* Unit tests for {@link RelativeRedirectFilter}.
3340
* @author Rob Winch
34-
* @since 4.3.10
3541
*/
3642
@RunWith(MockitoJUnitRunner.class)
3743
public class RelativeRedirectFilterTests {
44+
3845
@Mock
3946
HttpServletResponse response;
4047

4148
RelativeRedirectFilter filter = new RelativeRedirectFilter();
4249

50+
4351
@Test(expected = IllegalArgumentException.class)
4452
public void sendRedirectHttpStatusWhenNullThenIllegalArgumentException() {
45-
this.filter.setSendRedirectHttpStatus(null);
53+
this.filter.setRedirectStatus(null);
4654
}
4755

4856
@Test(expected = IllegalArgumentException.class)
4957
public void sendRedirectHttpStatusWhenNot3xxThenIllegalArgumentException() {
50-
this.filter.setSendRedirectHttpStatus(HttpStatus.OK);
58+
this.filter.setRedirectStatus(HttpStatus.OK);
5159
}
5260

5361
@Test
54-
public void doFilterSendRedirectWhenDefaultsThenLocationAnd302() throws Exception {
62+
public void doFilterSendRedirectWhenDefaultsThenLocationAnd303() throws Exception {
5563
String location = "/foo";
56-
5764
sendRedirect(location);
5865

5966
InOrder inOrder = Mockito.inOrder(this.response);
67+
inOrder.verify(this.response).setStatus(HttpStatus.SEE_OTHER.value());
6068
inOrder.verify(this.response).setHeader(HttpHeaders.LOCATION, location);
61-
inOrder.verify(this.response).setStatus(HttpStatus.FOUND.value());
6269
}
6370

6471
@Test
6572
public void doFilterSendRedirectWhenCustomSendRedirectHttpStatusThenLocationAnd301() throws Exception {
6673
String location = "/foo";
6774
HttpStatus status = HttpStatus.MOVED_PERMANENTLY;
68-
this.filter.setSendRedirectHttpStatus(status);
75+
this.filter.setRedirectStatus(status);
6976
sendRedirect(location);
7077

7178
InOrder inOrder = Mockito.inOrder(this.response);
72-
inOrder.verify(this.response).setHeader(HttpHeaders.LOCATION, location);
7379
inOrder.verify(this.response).setStatus(status.value());
80+
inOrder.verify(this.response).setHeader(HttpHeaders.LOCATION, location);
7481
}
7582

76-
private void sendRedirect(String location) throws Exception {
83+
@Test
84+
public void wrapOnceOnly() throws Exception {
85+
HttpServletResponse original = new MockHttpServletResponse();
86+
7787
MockFilterChain chain = new MockFilterChain();
88+
this.filter.doFilterInternal(new MockHttpServletRequest(), original, chain);
89+
90+
HttpServletResponse wrapped1 = (HttpServletResponse) chain.getResponse();
91+
assertNotSame(original, wrapped1);
7892

79-
filter.doFilterInternal(new MockHttpServletRequest(), response, chain);
93+
chain.reset();
94+
this.filter.doFilterInternal(new MockHttpServletRequest(), wrapped1, chain);
95+
HttpServletResponse current = (HttpServletResponse) chain.getResponse();
96+
assertSame(wrapped1, current);
97+
98+
chain.reset();
99+
HttpServletResponse wrapped2 = new HttpServletResponseWrapper(wrapped1);
100+
this.filter.doFilterInternal(new MockHttpServletRequest(), wrapped2, chain);
101+
current = (HttpServletResponse) chain.getResponse();
102+
assertSame(wrapped2, current);
103+
}
104+
105+
106+
private void sendRedirect(String location) throws Exception {
107+
MockFilterChain chain = new MockFilterChain();
108+
this.filter.doFilterInternal(new MockHttpServletRequest(), this.response, chain);
80109

81110
HttpServletResponse wrappedResponse = (HttpServletResponse) chain.getResponse();
82111
wrappedResponse.sendRedirect(location);

0 commit comments

Comments
 (0)