HTTP

所有基於 HTTP 的通訊都應 使用 TLS 進行保護

本節討論了有助於使用 HTTPS 的 Servlet 特定功能的詳細資訊。

重定向到 HTTPS

如果客戶端使用 HTTP 而非 HTTPS 發起請求,可以配置 Spring Security 以重定向到 HTTPS。

例如,以下 Java 或 Kotlin 配置會將任何 HTTP 請求重定向到 HTTPS

重定向到 HTTPS
  • Java

  • Kotlin

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
			// ...
			.requiresChannel(channel -> channel
				.anyRequest().requiresSecure()
			);
		return http.build();
	}
}
@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    open fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            // ...
            requiresChannel {
                secure(AnyRequestMatcher.INSTANCE, "REQUIRES_SECURE_CHANNEL")
            }
        }
        return http.build()
    }
}

以下 XML 配置會將所有 HTTP 請求重定向到 HTTPS

使用 XML 配置重定向到 HTTPS
<http>
	<intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
...
</http>

Strict Transport Security

Spring Security 支援 Strict Transport Security,並預設啟用它。

代理伺服器配置

Spring Security 集成了代理伺服器