Spring webflux: redirect http to https

Zufar Muhamadeev :

How can i configure http->https redirect in spring webflux? I need all http request be redirected to https(as i understood any http request should have 301 http status response with change http->https). Didn't found any information about it in documentation. I found this answer, but it related to tomcat. I have netty.

Zufar Muhamadeev :

I found way, hope it helps somebody:

@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);
        }
    };
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474676&siteId=1