HTTP
Redirect to HTTPS
如果客户端使用 HTTP 而非 HTTPS 发出请求,你可以配置 Spring Security 重定向到 HTTPS。
If a client makes a request using HTTP rather than HTTPS, you can configure Spring Security to redirect to HTTPS.
以下 Java 配置会将任何 HTTP 请求重定向到 HTTPS:
The following Java configuration redirects any HTTP requests to HTTPS:
-
Java
-
Kotlin
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.redirectToHttps(withDefaults());
return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
// ...
redirectToHttps { }
}
}
您可以将该配置包装到一个 if
语句中,以便仅在生产中启用。或者,您可以通过寻找仅在生产中发生的有关请求的属性来启用它。例如,如果生产环境添加了一个名为 X-Forwarded-Proto
的标头,您应该使用以下 Java 配置:
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:
-
Java
-
Kotlin
@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 提供 Strict Transport Security 的支持并默认启用它。
Spring Security provides support for Strict Transport Security and enables it by default.
Proxy Server Configuration
Spring Security integrates with proxy servers 。
Spring Security integrates with proxy servers.