安全

本節解答了在使用 Spring Boot 時有關安全性的問題,包括將 Spring Security 與 Spring Boot 一起使用時出現的問題。

有關 Spring Security 的更多資訊,請參閱 Spring Security 專案頁面

關閉 Spring Boot 安全配置

如果在應用程式中定義了帶有 SecurityFilterChain bean 的 @Configuration,此操作將關閉 Spring Boot 中的預設 Web 應用程式安全設定。

更改 UserDetailsService 並新增使用者賬戶

如果提供型別為 AuthenticationManagerAuthenticationProviderUserDetailsService@Bean,則不會建立 InMemoryUserDetailsManager 的預設 @Bean。這意味著您可以使用 Spring Security 的完整功能集(例如各種認證選項)。

新增使用者賬戶最簡單的方法是提供自己的 UserDetailsService bean。

在代理伺服器後執行啟用 HTTPS

確保所有主要端點僅透過 HTTPS 可用是任何應用程式的一項重要任務。如果使用 Tomcat 作為 Servlet 容器,那麼 Spring Boot 會在檢測到某些環境設定時自動新增 Tomcat 自己的 RemoteIpValve,允許您依賴 HttpServletRequest 來報告它是否安全(即使在處理真實 SSL 終止的代理伺服器下游)。標準行為由某些請求頭(x-forwarded-forx-forwarded-proto)的存在或缺失決定,它們的名稱是約定俗成的,因此它應該適用於大多數前端代理。您可以透過在 application.properties 中新增一些條目來啟用該閥門,如以下示例所示:

  • 屬性

  • YAML

server.tomcat.remoteip.remote-ip-header=x-forwarded-for
server.tomcat.remoteip.protocol-header=x-forwarded-proto
server:
  tomcat:
    remoteip:
      remote-ip-header: "x-forwarded-for"
      protocol-header: "x-forwarded-proto"

(存在這些屬性中的任何一個都會啟用該閥門。或者,您可以透過使用 WebServerFactoryCustomizer bean 自定義 TomcatServletWebServerFactory 來新增 RemoteIpValve。)

要配置 Spring Security 以要求所有(或部分)請求使用安全通道,請考慮新增自己的 SecurityFilterChain bean,其中添加了以下 HttpSecurity 配置:

  • Java

  • Kotlin

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class MySecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) {
		// Customize the application security ...
		http.redirectToHttps(Customizer.withDefaults());
		return http.build();
	}

}
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain

@Configuration
class MySecurityConfig {

	@Bean
	fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
		// Customize the application security ...
		http.redirectToHttps { }
		return http.build()
	}

}
© . This site is unofficial and not affiliated with VMware.