如何在spring webflux中配置http-> https重定向?我需要将所有http
请求重定向到https
(据我了解,任何http
请求都应该301
http状态响应,并且更改为http-> https)。在documentation中未找到任何相关信息。
我找到了这个answer,但它与tomcat有关。我有网。
答案 0 :(得分:6)
我找到了方法,希望它有所帮助:
@Bean
public WebFilter httpsRedirectFilter() {
return new WebFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
URI originalUri = exchange.getRequest().getURI();
//here set your condition to http->https redirect
List<String> forwardedValues = exchange.getRequest().getHeaders().get("x-forwarded-proto");
if (forwardedValues != null && forwardedValues.contains("http")) {
try {
URI mutatedUri = new URI("https",
originalUri.getUserInfo(),
originalUri.getHost(),
originalUri.getPort(),
originalUri.getPath(),
originalUri.getQuery(),
originalUri.getFragment());
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
response.getHeaders().setLocation(mutatedUri);
return Mono.empty();
} catch (URISyntaxException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
return chain.filter(exchange);
}
};
}
答案 1 :(得分:1)
我设法使其适用于以下情况。但是,我怀疑这是否受支持,并且将来可能会引起问题。
@Configuration
public class HttpToHttpsRedirectConfig {
@PostConstruct
public void startRedirectServer() {
NettyReactiveWebServerFactory httpNettyReactiveWebServerFactory = new NettyReactiveWebServerFactory(8080);
httpNettyReactiveWebServerFactory.getWebServer((request, response) -> {
URI uri = request.getURI();
URI httpsUri;
try {
httpsUri = new URI("https", uri.getUserInfo(), uri.getHost(), 8443, uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
return Mono.error(e);
}
response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
response.getHeaders().setLocation(httpsUri);
return response.setComplete();
}).start();
}
}