深入淺析Spring Security5中默認密碼編碼器
1.概述
在Spring Security 4中,可以使用內(nèi)存中身份驗證以純文本格式存儲密碼。
對版本5中的密碼管理過程進行了重大改進,為密碼編碼和解碼引入了更安全的默認機制。這意味著如果您的Spring應用程序以純文本格式存儲密碼,升級到Spring Security 5可能會導致問題。
在這個簡短的教程中,我們將描述其中一個潛在的問題,并展示該問題的解決方案。
2. Spring Security 4
我們首先展示一個標準的安全配置,它提供簡單的內(nèi)存中身份驗證(適用于Spring 4):
@Configuration
public class InMemoryAuthWebSecurityConfigurer
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("spring")
.password("secret")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/private/**")
.authenticated()
.antMatchers("/public/**")
.permitAll()
.and()
.httpBasic();
}
}
此配置定義所有/私有/映射方法的身份驗證以及/ public /下所有內(nèi)容的公共訪問。
如果我們在Spring Security 5下使用相同的配置,我們會收到以下錯誤:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
該錯誤告訴我們由于沒有為我們的內(nèi)存中身份驗證配置密碼編碼器,因此無法解碼給定的密碼。
3. Spring Security 5
我們可以通過使用PasswordEncoderFactories類定義DelegatingPasswordEncoder來解決此錯誤。
我們使用此編碼器通過AuthenticationManagerBuilder配置我們的用戶:
@Configuration
public class InMemoryAuthWebSecurityConfigurer
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.inMemoryAuthentication()
.withUser("spring")
.password(encoder.encode("secret"))
.roles("USER");
}
}
現(xiàn)在,通過這種配置,我們使用BCrypt以以下格式存儲我們的內(nèi)存中密碼:
{bcrypt}$2a$10$MF7hYnWLeLT66gNccBgxaONZHbrSMjlUofkp50sSpBw2PJjUqU.zS
雖然我們可以定義自己的一組密碼編碼器,但建議堅持使用PasswordEncoderFactories中提供的默認編碼器。
3.1.遷移現(xiàn)有密碼
我們可以通過以下方式將現(xiàn)有密碼更新為推薦的Spring Security 5標準:
更新純文本存儲密碼及其編碼值:
String encoded = new BCryptPasswordEncoder().encode(plainTextPassword);
前綴散列存儲的密碼及其已知的編碼器標識符:
{bcrypt}$2a$10$MF7hYnWLeLT66gNccBgxaONZHbrSMjlUofkp50sSpBw2PJjUqU.zS
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0
當存儲密碼的編碼機制未知時,請求用戶更新其密碼
4.結(jié)論
在這個快速示例中,我們使用新的密碼存儲機制將有效的Spring 4內(nèi)存中認證配置更新到Spring 5。
與往常一樣,您可以在GitHub項目中找到源代碼。
總結(jié)
以上所述是小編給大家介紹的Spring Security 5中默認密碼編碼器,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關文章
Spring Boot中Redis數(shù)據(jù)庫的使用實例
Spring Boot中除了對常用的關系型數(shù)據(jù)庫提供了優(yōu)秀的自動化支持之外,對于很多NoSQL數(shù)據(jù)庫一樣提供了自動化配置的支持。本篇文章主要介紹了Spring Boot中Redis的使用實例代碼,有興趣的開業(yè)了解一下。2017-04-04
關于Java中String創(chuàng)建的字符串對象內(nèi)存分配測試問題
這篇文章主要介紹了Java中String創(chuàng)建的字符串對象內(nèi)存分配測試,給大家詳細介紹了在創(chuàng)建String對象的兩種常用方法比較,通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2021-07-07
springboot2.2 集成 activity6實現(xiàn)請假流程(示例詳解)
這篇文章主要介紹了springboot2.2 集成 activity6實現(xiàn)請假完整流程示例詳解,本文通過示例代碼圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

