1
0
mirror of synced 2026-08-03 08:51:58 +00:00

Reactive Redirect to Https

This introduces the capability to configure Reactive Spring Security
to upgrade requests to HTTPS

Fixes: gh-5749
This commit is contained in:
Josh Cummings
2018-08-30 10:35:13 -06:00
committed by Rob Winch
parent f164f2f869
commit 2c982a4168
5 changed files with 515 additions and 1 deletions
@@ -0,0 +1,110 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.server.transport;
import java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.PortMapperImpl;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.UriComponentsBuilder;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.anyExchange;
/**
* Redirects any non-HTTPS request to its HTTPS equivalent.
*
* Can be configured to use a {@link ServerWebExchangeMatcher} to narrow which requests get redirected.
*
* Can also be configured for custom ports using {@link PortMapper}.
*
* @author Josh Cummings
* @since 5.1
*/
public final class HttpsRedirectWebFilter implements WebFilter {
private PortMapper portMapper = new PortMapperImpl();
private ServerWebExchangeMatcher requiresHttpsRedirectMatcher = anyExchange();
private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return Mono.just(exchange)
.filter(this::isInsecure)
.flatMap(this.requiresHttpsRedirectMatcher::matches)
.filter(matchResult -> matchResult.isMatch())
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.map(matchResult -> createRedirectUri(exchange))
.flatMap(uri -> this.redirectStrategy.sendRedirect(exchange, uri));
}
/**
* Use this {@link PortMapper} for mapping custom ports
*
* @param portMapper the {@link PortMapper} to use
*/
public void setPortMapper(PortMapper portMapper) {
Assert.notNull(portMapper, "portMapper cannot be null");
this.portMapper = portMapper;
}
/**
* Use this {@link ServerWebExchangeMatcher} to narrow which requests are redirected to HTTPS.
*
* The filter already first checks for HTTPS in the uri scheme, so it is not necessary
* to include that check in this matcher.
*
* @param requiresHttpsRedirectMatcher the {@link ServerWebExchangeMatcher} to use
*/
public void setRequiresHttpsRedirectMatcher
(ServerWebExchangeMatcher requiresHttpsRedirectMatcher) {
Assert.notNull(requiresHttpsRedirectMatcher,
"requiresHttpsRedirectMatcher cannot be null");
this.requiresHttpsRedirectMatcher = requiresHttpsRedirectMatcher;
}
private Boolean isInsecure(ServerWebExchange exchange) {
return !"https".equals(exchange.getRequest().getURI().getScheme());
}
private URI createRedirectUri(ServerWebExchange exchange) {
int port = exchange.getRequest().getURI().getPort();
UriComponentsBuilder builder =
UriComponentsBuilder.fromUri(exchange.getRequest().getURI());
if (port > 0) {
port = this.portMapper.lookupHttpsPort(port);
builder.port(port);
}
return builder.scheme("https").build().toUri();
}
}
@@ -0,0 +1,149 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.server.transport;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link HttpsRedirectWebFilter}
*
* @author Josh Cummings
*/
@RunWith(MockitoJUnitRunner.class)
public class HttpsRedirectWebFilterTests {
HttpsRedirectWebFilter filter;
@Mock
WebFilterChain chain;
@Before
public void configureFilter() {
this.filter = new HttpsRedirectWebFilter();
when(this.chain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty());
}
@Test
public void filterWhenExchangeIsInsecureThenRedirects() {
ServerWebExchange exchange = get("http://localhost");
this.filter.filter(exchange, this.chain).block();
assertThat(statusCode(exchange)).isEqualTo(302);
assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost");
}
@Test
public void filterWhenExchangeIsSecureThenNoRedirect() {
ServerWebExchange exchange = get("https://localhost");
this.filter.filter(exchange, this.chain).block();
assertThat(exchange.getResponse().getStatusCode()).isNull();
}
@Test
public void filterWhenExchangeMismatchesThenNoRedirect() {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
when(matcher.matches(any(ServerWebExchange.class)))
.thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
this.filter.filter(exchange, this.chain).block();
assertThat(exchange.getResponse().getStatusCode()).isNull();
}
@Test
public void filterWhenExchangeMatchesAndRequestIsInsecureThenRedirects() {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
when(matcher.matches(any(ServerWebExchange.class)))
.thenReturn(ServerWebExchangeMatcher.MatchResult.match());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
this.filter.filter(exchange, this.chain).block();
assertThat(statusCode(exchange)).isEqualTo(302);
assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:8443");
verify(matcher).matches(any(ServerWebExchange.class));
}
@Test
public void filterWhenRequestIsInsecureThenPortMapperRemapsPort() {
PortMapper portMapper = mock(PortMapper.class);
when(portMapper.lookupHttpsPort(314)).thenReturn(159);
this.filter.setPortMapper(portMapper);
ServerWebExchange exchange = get("http://localhost:314");
this.filter.filter(exchange, this.chain).block();
assertThat(statusCode(exchange)).isEqualTo(302);
assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:159");
verify(portMapper).lookupHttpsPort(314);
}
@Test
public void filterWhenInsecureRequestHasAPathThenRedirects() {
ServerWebExchange exchange = get("http://localhost:8080/path/page.html?query=string");
this.filter.filter(exchange, this.chain).block();
assertThat(statusCode(exchange)).isEqualTo(302);
assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:8443/path/page.html?query=string");
}
@Test
public void setRequiresTransportSecurityMatcherWhenSetWithNullValueThenThrowsIllegalArgument() {
assertThatCode(() -> this.filter.setRequiresHttpsRedirectMatcher(null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void setPortMapperWhenSetWithNullValueThenThrowsIllegalArgument() {
assertThatCode(() -> this.filter.setPortMapper(null))
.isInstanceOf(IllegalArgumentException.class);
}
private String redirectedUrl(ServerWebExchange exchange) {
return exchange.getResponse().getHeaders().get(HttpHeaders.LOCATION)
.iterator().next();
}
private int statusCode(ServerWebExchange exchange) {
return exchange.getResponse().getStatusCode().value();
}
private ServerWebExchange get(String uri) {
return MockServerWebExchange.from(
MockServerHttpRequest.get(uri).build());
}
}