Spring Security靈活的PasswordEncoder加密方式解析
導(dǎo)讀
本章基于Spring Security 5.4.1版本編寫(xiě),從5.x版本開(kāi)始引入了很多新的特性。
為了適配老系統(tǒng)的安全框架升級(jí),Spring Security也是費(fèi)勁了心思,支持不同的密碼加密方式,而且根據(jù)不同的用戶可以使用不同的加密方式。
構(gòu)建Spring Security項(xiàng)目
Spring Security的集成使用還是很簡(jiǎn)單的,根據(jù)項(xiàng)目使用的框架不同大致分為兩種集成方式:
SpringBoot方式集成
SecurityBom方式集成
SpringBoot方式構(gòu)建
在pom.xml文件內(nèi)添加如下內(nèi)容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>SecurityBom方式構(gòu)建
spring-security-bom是一個(gè)提供了Spring Security指定版本的全部默認(rèn)依賴的pom類型項(xiàng)目,我們可以通過(guò)dependencyManagement進(jìn)行配置到項(xiàng)目中,這樣我們就可以直接添加對(duì)應(yīng)的dependency了(注意:版本號(hào)因?yàn)閎om已經(jīng)注定,所以dependency不需要指定.)。
在pom.xml文件內(nèi)添加如下內(nèi)容:
<dependencies>
// ...省略其他依賴
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!--配置SecurityBom-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-bom</artifactId>
<version>5.4.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>注意事項(xiàng):我們構(gòu)建Web類型的安全項(xiàng)目時(shí),spring-security-config、spring-security-core、spring-security-web三個(gè)依賴都是必須添加的。
PasswordEncoder
PasswordEncoder是Spring Security提供的密碼加密方式的接口定義,源碼類如下所示:
public interface PasswordEncoder {
/**
* Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or
* greater hash combined with an 8-byte or greater randomly generated salt.
*/
String encode(CharSequence rawPassword);
/**
* Verify the encoded password obtained from storage matches the submitted raw
* password after it too is encoded. Returns true if the passwords match, false if
* they do not. The stored password itself is never decoded.
*
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from
* storage
*/
boolean matches(CharSequence rawPassword, String encodedPassword);
/**
* Returns true if the encoded password should be encoded again for better security,
* else false. The default implementation always returns false.
* @param encodedPassword the encoded password to check
* @return true if the encoded password should be encoded again for better security,
* else false.
*/
default boolean upgradeEncoding(String encodedPassword) {
return false;
}
}#encode
該方法提供了明文密碼的加密處理,加密后密文的格式主要取決于
PasswordEncoder接口實(shí)現(xiàn)類實(shí)例。#matches
匹配存儲(chǔ)的密碼以及登錄時(shí)傳遞的密碼(
登錄密碼是經(jīng)過(guò)加密處理后的字符串)是否匹配,如果匹配該方法則會(huì)返回true.
內(nèi)置的PasswordEncoder實(shí)現(xiàn)列表
NoOpPasswordEncoder(已廢除)
明文密碼加密方式,該方式已被廢除(不建議在生產(chǎn)環(huán)境使用),不過(guò)還是支持開(kāi)發(fā)階段測(cè)試Spring Security的時(shí)候使用。
DelegatingPasswordEncoder
在之前版本集成Spring Secuirty時(shí),我們需要通過(guò)@Bean的方式來(lái)配置全局統(tǒng)一使用的密碼加密方式(PasswordEncoder),當(dāng)然這種方式現(xiàn)在還是適用的,不過(guò)在5.x版本開(kāi)始為了支持動(dòng)態(tài)的多種密碼加密方式,DelegatingPasswordEncoder委托加密方式類應(yīng)用而生,它內(nèi)部其實(shí)是一個(gè)Map集合,根據(jù)傳遞的Key(Key為加密方式)獲取Map集合的Value,而Value則是具體的PasswordEncoder實(shí)現(xiàn)類。
DelegatingPasswordEncoder建立密碼格式的規(guī)則,格式如:{bcrypt}encodePassword,示例如下所示:
// {bcrypt}格式會(huì)委托給BCryptPasswordEncoder加密類
{bcrypt}$2a$10$iMz8sMVMiOgRgXRuREF/f.ChT/rpu2ZtitfkT5CkDbZpZlFhLxO3y
// {pbkdf2}格式會(huì)委托給Pbkdf2PasswordEncoder加密類
{pbkdf2}cc409867e39f011f6332bbb6634f58e98d07be7fceefb4cc27e62501594d6ed0b271a25fd9f7fc2e
// {MD5}格式會(huì)委托給MessageDigestPasswordEncoder加密類
{MD5}e10adc3949ba59abbe56e057f20f883e
// {noop}明文方式,委托給NoOpPasswordEncoder
{noop}123456
// ...指定用戶使用PasswordEncoder
DelegatingPasswordEncoder是默認(rèn)的PasswordEncoder加密方式,所以我們可以為不同的用戶配置所使用不同的密碼加密方式,只需要密碼格式按照:{away}encodePassword來(lái)進(jìn)行持久化即可。
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/**")
.authenticated();
}
@Bean
public UserDetailsService users() {
// {MD5}value必須大寫(xiě),value值必須是32位小寫(xiě)
// admin
UserDetails admin = User.builder()
//.passwordEncoder(encoder::encode)
.username("admin").password(
"{MD5}e10adc3949ba59abbe56e057f20f883e"
).roles("admin").build();
// hengboy
UserDetails hengboy = User.builder()
.username("hengboy")
.password("{bcrypt}$2a$10$iMz8sMVMiOgRgXRuREF/f.ChT/rpu2ZtitfkT5CkDbZpZlFhLxO3y")
.roles("admin")
.build();
// yuqiyu
UserDetails yuqiyu = User.builder().username("yuqiyu")
//.password("{noop}123456")
.password("{pbkdf2}cc409867e39f011f6332bbb6634f58e98d07be7fceefb4cc27e62501594d6ed0b271a25fd9f7fc2e")
.roles("user").build();
return new InMemoryUserDetailsManager(admin, yuqiyu, hengboy);
}
}上面是使用內(nèi)存方式存儲(chǔ)安全用戶的實(shí)現(xiàn)代碼,在創(chuàng)建UserDetailsService類的實(shí)例時(shí)將用戶列表通過(guò)構(gòu)造參數(shù)進(jìn)行傳遞。
所創(chuàng)建的用戶:admin,采用MD5的加密方式進(jìn)行密碼編碼,這里需要注意的是MD5加密后的字符串必須為小寫(xiě)32位。
所創(chuàng)建的用戶:hengboy,采用bcrypt方式進(jìn)行密碼編碼。
所創(chuàng)建的用戶:yuqiyu,采用pbkdf2方式進(jìn)行密碼編碼。
覆蓋默認(rèn)的PasswordEncoder
Spring Security 5.x版本默認(rèn)的PasswordEncoder方式改成了DelegatingPasswordEncoder委托類,不過(guò)如果是通過(guò)PasswordEncoderFactories#createDelegatingPasswordEncoder方法創(chuàng)建的DelegatingPasswordEncoder實(shí)例時(shí),默認(rèn)其實(shí)使用的還是BCryptPasswordEncoder,源碼如下所示:
public static PasswordEncoder createDelegatingPasswordEncoder() {
String encodingId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encodingId, new BCryptPasswordEncoder());
// 省略...
return new DelegatingPasswordEncoder(encodingId, encoders);
}如果我們項(xiàng)目中不需要使用DelegatingPasswordEncoder委托密碼編碼方式,可以通過(guò)@Bean的方式來(lái)統(tǒng)一配置全局共用的PasswordEncoder,如下所示:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
可以根據(jù)項(xiàng)目自行選擇所使用的PasswordEncoder實(shí)現(xiàn)類。
以上就是Spring Security靈活的PasswordEncoder加密方式解析的詳細(xì)內(nèi)容,更多關(guān)于Spring Security PasswordEncoder加密的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 使用spring?security?BCryptPasswordEncoder接入系統(tǒng)
- Spring?Security密碼解析器PasswordEncoder自定義登錄邏輯
- Spring security BCryptPasswordEncoder密碼驗(yàn)證原理詳解
- 一文掌握SpringSecurity?BCrypt密碼加密和解密
- Spring?Security如何實(shí)現(xiàn)升級(jí)密碼加密方式詳解
- Spring Security基于散列加密方案實(shí)現(xiàn)自動(dòng)登錄功能
- Spring security密碼加密實(shí)現(xiàn)代碼實(shí)例
相關(guān)文章
mybatis?實(shí)現(xiàn)多層級(jí)collection嵌套
這篇文章主要介紹了mybatis?實(shí)現(xiàn)多層級(jí)collection嵌套,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
解決lambda表達(dá)式內(nèi)出現(xiàn)異常無(wú)法throw拋出的問(wèn)題
這篇文章主要介紹了lambda表達(dá)式內(nèi)出現(xiàn)異常無(wú)法throw拋出的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java多線程教程之如何利用Future實(shí)現(xiàn)攜帶結(jié)果的任務(wù)
Callable與Future兩功能是Java?5版本中加入的,這篇文章主要給大家介紹了關(guān)于Java多線程教程之如何利用Future實(shí)現(xiàn)攜帶結(jié)果任務(wù)的相關(guān)資料,需要的朋友可以參考下2021-12-12
關(guān)于SpringBoot+Mybatis報(bào)MapperScan.factoryBean()問(wèn)題
解決SpringBoot+Mybatis中的MapperScan.factoryBean()問(wèn)題,讓你的項(xiàng)目運(yùn)行更順暢!本指南將帶你一步步解決這個(gè)問(wèn)題,讓你的開(kāi)發(fā)過(guò)程更加高效,不要錯(cuò)過(guò)這個(gè)實(shí)用指南,快來(lái)一探究竟吧!2024-02-02
elasticsearch 8.2.3 安裝及springboot簡(jiǎn)單使用
這篇文章主要介紹了elasticsearch 8.2.3 安裝及springboot簡(jiǎn)單使用,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
CommonMark 使用教程:將 Markdown 語(yǔ)法轉(zhuǎn)成 Html
這篇文章主要介紹了CommonMark 使用教程:將 Markdown 語(yǔ)法轉(zhuǎn)成 Html,這個(gè)技巧我們做任何網(wǎng)站都可以用到,而且非常好用。,需要的朋友可以參考下2019-06-06
SpringBoot中使用?ThreadLocal?進(jìn)行多線程上下文管理及注意事項(xiàng)小結(jié)
本文詳細(xì)介紹了ThreadLocal的原理、使用場(chǎng)景和示例代碼,并在SpringBoot中使用ThreadLocal保存請(qǐng)求中攜帶的用戶信息,ThreadLocal通過(guò)為每個(gè)線程維護(hù)獨(dú)立的變量副本,解決了線程安全問(wèn)題,感興趣的朋友一起看看吧2025-02-02

