HTTP

All HTTP-based communication should be protected with using TLS.spring-doc.cn

This section covers details about using WebFlux-specific features that assist with HTTPS usage.spring-doc.cn

Redirect to HTTPS

If a client makes a request using HTTP rather than HTTPS, you can configure Spring Security to redirect to HTTPS.spring-doc.cn

The following Java configuration redirects any HTTP requests to HTTPS:spring-doc.cn

Redirect to HTTPS
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
	http
		// ...
		.redirectToHttps(withDefaults());
	return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        // ...
        redirectToHttps { }
    }
}

You can wrap the configuration can be wrapped around an if statement to be turned on only in production. Alternatively, you can enable it by looking for a property about the request that happens only in production. For example, if the production environment adds a header named X-Forwarded-Proto, you should use the following Java Configuration:spring-doc.cn

Redirect to HTTPS when X-Forwarded
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
	http
		// ...
		.redirectToHttps(redirect -> redirect
			.httpsRedirectWhen(e -> e.getRequest().getHeaders().containsKey("X-Forwarded-Proto"))
		);
	return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        // ...
        redirectToHttps {
            httpsRedirectWhen {
                it.request.headers.containsKey("X-Forwarded-Proto")
            }
        }
    }
}

Strict Transport Security

Spring Security provides support for Strict Transport Security and enables it by default.spring-doc.cn

Proxy Server Configuration