Spring?Security密碼解析器PasswordEncoder自定義登錄邏輯
一、PasswordEncoder密碼解析器詳解
Spring Security要求容器中必須有PasswordEncoder實例。所以當(dāng)自定義登錄邏輯時要求必須給容器注入PaswordEncoder的bean對象
1.接口介紹
- encode():把參數(shù)按照特定的解析規(guī)則進行解析。
- matches()驗證從存儲中獲取的編碼密碼與編碼后提交的原始密碼是否匹配。如果密碼匹配,則返回true;如果不匹配,則返回false。第一個參數(shù)表示需要被解析的密碼。第二個參數(shù)表示存儲的密碼。
- upgradeEncoding():如果解析的密碼能夠再次進行解析且達到更安全的結(jié)果則返回true,否則返回false。默認返回false。
2.內(nèi)置解析器介紹
在Spring Security中內(nèi)置了很多解析器。
3.BCryptPasswordEncoder簡介
BCryptPasswordEncoder是Spring Security官方推薦的密碼解析器,平時多使用這個解析器。
BCryptPasswordEncoder是對bcrypt強散列方法的具體實現(xiàn)。是基于Hash算法實現(xiàn)的單向加密。可以通過strength控制加密強度,默認10.
4.代碼演示
在項目src/test/java下新建com.msb.MyTest測試BCryptPasswordEncoder用法。
@SpringBootTest @RunWith(SpringRunner.class) public class MyTest { @Test public void test(){ //創(chuàng)建解析器 PasswordEncoder encoder = new BCryptPasswordEncoder(); //對密碼進行加密 String password = encoder.encode("123"); System.out.println("------------"+password); //判斷原字符加密后和內(nèi)容是否匹配 boolean result = encoder.matches("123",password); System.out.println("============="+result); } }
二、自定義登錄邏輯
當(dāng)進行自定義登錄邏輯時需要用到之前講解的UserDetailsService和PasswordEncoder。但是Spring Security要求:當(dāng)進行自定義登錄邏輯時容器內(nèi)必須有PasswordEncoder實例。所以不能直接new對象。
1.編寫配置類
新建類com.msb.config.SecurityConfig 編寫下面內(nèi)容
@Configuration public class SecurityConfig { @Bean public PasswordEncoder getPwdEncoder(){ return new BCryptPasswordEncoder(); } }
2.自定義邏輯
在Spring Security中實現(xiàn)UserDetailService就表示為用戶詳情服務(wù)。在這個類中編寫用戶認證邏輯。
@Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private PasswordEncoder encoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //1. 查詢數(shù)據(jù)庫判斷用戶名是否存在,如果不存在拋出UsernameNotFoundException if(!username.equals("admin")){ throw new UsernameNotFoundException("用戶名不存在"); } //把查詢出來的密碼進行解析,或直接把password放到構(gòu)造方法中。 //理解:password就是數(shù)據(jù)庫中查詢出來的密碼,查詢出來的內(nèi)容不是123 String password = encoder.encode("123"); return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); } }
3.查看效果
重啟項目后,在瀏覽器中輸入賬號:admin,密碼:123。后可以正確進入到login.html頁面。
以上就是Spring Security密碼解析器PasswordEncoder自定義登錄邏輯的詳細內(nèi)容,更多關(guān)于Spring Security PasswordEncoder的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring之AOP兩種代理機制對比分析(JDK和CGLib動態(tài)代理)
這篇文章主要介紹了Spring之AOP兩種代理機制對比分析(JDK和CGLib動態(tài)代理),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05Java實現(xiàn)鏈表數(shù)據(jù)結(jié)構(gòu)的方法
這篇文章主要介紹了Java實現(xiàn)鏈表數(shù)據(jù)結(jié)構(gòu)的相關(guān)資料,每一個鏈表都包含多個節(jié)點,節(jié)點又包含兩個部分,一個是數(shù)據(jù)域(儲存節(jié)點含有的信息),一個是引用域(儲存下一個節(jié)點或者上一個節(jié)點的地址),需要的朋友可以參考下2022-01-01SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn)
本文主要介紹了SpringBoot中數(shù)據(jù)傳輸對象(DTO)的實現(xiàn),包括了手動創(chuàng)建DTO、使用ModelMapper和Lombok創(chuàng)建DTO的示例,具有一定的參考價值,感興趣的可以了解一下2024-07-07Feign 集成 Hystrix實現(xiàn)不同的調(diào)用接口不同的設(shè)置方式
這篇文章主要介紹了Feign 集成 Hystrix實現(xiàn)不同的調(diào)用接口不同的設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06