天天看點

spring boot 2進階篇(11)——安全

安全

本節讨論有關使用Spring Boot時的安全性問題,包括使用Spring Security和Spring Boot引起的問題。

有關Spring Security的更多資訊,請參閱Spring Security項目頁面。

關閉Spring Boot安全配置

不管你在應用的什麼地方定義了一個使用@EnableWebSecurity注解的@Configuration,它都會關閉Spring Boot中的預設webapp安全設定。想要調整預設值,你可以嘗試設定security.*屬性(具體檢視SecurityProperties和常見應用屬性的SECURITY章節)。

改變AuthenticationManager并添加使用者賬号

如果你提供了一個AuthenticationManager類型的@Bean,那麼預設的就不會被建立了,是以你可以獲得Spring Security可用的全部特性(比如,不同的認證選項)。

Spring Security也提供了一個友善的AuthenticationManagerBuilder,用于建構具有常見選項的AuthenticationManager。在一個webapp中,推薦将它注入到WebSecurityConfigurerAdapter的一個void方法中,比如:

@Configuration

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication()

.withUser("barry").password("password").roles("USER"); // ... etc.

}

// ... other stuff for application security

}

如果把它放到一個内部類或一個單獨的類中,你将得到最好的結果(也就是不跟很多其他@Beans混合在一起将允許你改變執行個體化的順序)。secure web sample是一個有用的參考模闆。

如果你遇到了執行個體化問題(比如,使用JDBC或JPA進行使用者詳細資訊的存儲),那将AuthenticationManagerBuilder回調提取到一個GlobalAuthenticationConfigurerAdapter(放到init()方法内以防其他地方也需要authentication manager)可能是個不錯的選擇,比如:

@Configuration

public class AuthenticationManagerConfiguration extends

GlobalAuthenticationConfigurerAdapter {

@Override

public void init(AuthenticationManagerBuilder auth) {

auth.inMemoryAuthentication() // ... etc.

}

}

目前端使用代理伺服器時啟用HTTPS

對于任何應用來說,確定所有的主端點(URL)都隻在HTTPS下可用是個重要的苦差事。如果你使用Tomcat作為servlet容器,那Spring Boot如果發現一些環境設定的話,它将自動添加Tomcat自己的RemoteIpValve,你也可以依賴于HttpServletRequest來報告是否請求是安全的(即使代理伺服器的downstream處理真實的SSL終端)。這個标準行為取決于某些請求頭是否出現(x-forwarded-for和x-forwarded-proto),這些請求頭的名稱都是約定好的,是以對于大多數前端和代理都是有效的。

你可以向application.properties添加以下設定開啟該功能,比如:

server.tomcat.remote_ip_header=x-forwarded-for

server.tomcat.protocol_header=x-forwarded-proto