在ch05的講解中我們看到了用戶的信息被存儲(chǔ)到數(shù)據(jù)庫中仗谆,為用戶維護(hù)與信息共享提供了途徑圣絮。我們在應(yīng)用層面做好了安全的同時(shí)卻忽略了數(shù)據(jù)的安全似炎,用戶的密碼以明文的方式存儲(chǔ)在數(shù)據(jù)庫中犬缨,這成了新的危險(xiǎn)點(diǎn)。通過用戶密碼加密技術(shù)就可以解決這個(gè)問題恒削。Spring Security也提供了應(yīng)用層面密碼加密技術(shù)池颈,配置和應(yīng)用非常簡單。
在Spring Security中密碼加密通過PasswordEncoder實(shí)現(xiàn)钓丰。
springframework.security.authentication.encoding.PasswordEncoder
是Spring Security4.0之前使用的密碼加密技術(shù)躯砰,現(xiàn)在已經(jīng)不推薦使用了,建議使用能夠更好的提供隨機(jī)salt的新接口
org.springframework.security.crypto.password.PasswordEncoder
目前携丁,Spring Security建議使用BCryptPasswordEncoder琢歇,該加密算法可以定制密碼長度,密碼越長梦鉴,破解所需時(shí)間越多李茫,默認(rèn)長度為10。該算法較常用的MD5+隨機(jī)salt高效肥橙、易用且更加安全魄宏,且不需要在數(shù)據(jù)庫中擴(kuò)展salt字段。
為了支持密碼加密存筏,只需對WebSecurityConfigurerAdapter要進(jìn)行如下修改
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
auth
.jdbcAuthentication()
.passwordEncoder(passwordEncoder())//啟用密碼加密功能
.dataSource(dataSource);
}
/**
* 密碼加密算法
*
* @return
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
此外還需要對數(shù)據(jù)庫中儲(chǔ)存的明文進(jìn)行加密娜庇,否則用戶登錄界面輸入的密碼加密后與數(shù)據(jù)庫存儲(chǔ)的明文密碼不一致塔次,無法登錄。數(shù)據(jù)庫密碼加密可調(diào)用passwordEncoder的bean實(shí)現(xiàn)
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode("password");
完成以上步驟后名秀,登錄用戶輸入密碼,登錄成功藕溅。通過以上簡單配置即可實(shí)現(xiàn)應(yīng)用層面匕得、數(shù)據(jù)庫層面用戶密碼加密的功能,進(jìn)一步提高了系統(tǒng)的安全性巾表。
PS:結(jié)合ch04汁掠、ch05和ch06,調(diào)取passwordEncoder對用戶修改后的密碼加密集币,并儲(chǔ)存到數(shù)據(jù)庫中考阱,就可以實(shí)現(xiàn)具有基本功能的、且安全的用戶認(rèn)證管理過程鞠苟。
代碼示例https://github.com/wexgundam/spring.security/tree/master/ch06