纲要
PasswordEncoder核心接口与常见实现BCryptPasswordEncoderSCryptPasswordEncoderPbkdf2PasswordEncoderMessageDigestPasswordEncoder(MD5等,已弃用)
- 多密码编码器共存的设计需求
DelegatingPasswordEncoder:多算法共存与平滑升级- 构造方式与存储格式
{id}encodedPassword - 密码匹配流程与内部委托机制
- 构造方式与存储格式
- 实战:配置多种编码器并实现用户认证
- 密码升级策略:从旧算法迁移到更安全的编码
- 完整可运行代码示例(基于Spring Security配置)
- OAuth2场景中的适用说明
为什么需要密码编码器
在存储用户密码时,绝对不能使用明文。Spring Security 提供的 PasswordEncoder 接口负责将原始密码进行单向哈希编码,并在登录时校验密码。编码后的字符串应当对人类不可读,以此抵御数据库泄露后的彩虹表攻击。
Spring Security 内置的编码器
Spring Security 内置了多种主流编码器,开发时可以通过 PasswordEncoderFactories 直接获取默认实现,也可以按需指定:
BCryptPasswordEncoder:目前推荐的默认编码器,基于 bcrypt 强哈希算法,内建盐值,抗暴力破解。SCryptPasswordEncoder:内存消耗型哈希,对抗硬件加速攻击。Pbkdf2PasswordEncoder:基于 PBKDF2 算法,可配置迭代次数。MessageDigestPasswordEncoder:基于 MD5 / SHA-1 等消息摘要算法,已标记@Deprecated,仅保留用于兼容老系统。
若你直接注入 PasswordEncoder 的默认 Bean,通常拿到的就是 BCryptPasswordEncoder。我们可以在代码中快速验证其编码效果:
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String encoded = encoder.encode("12345678");
System.out.println(encoded);
// 输出类似: {bcrypt}$2a$10$...很长一串
每次编码结果均不同(盐值随机),因此即使相同明文也不会产生相同密文。
多算法共存的困境
系统经过多年迭代,很可能初期使用了 MD5 或 SHA-1 等已过时的编码器。如果直接全局替换为新算法,老用户将无法登录,因为数据库中保存的密码哈希无法被新编码器正确匹配。于是我们需要一种机制:支持多种编码器同时存在,并能自动识别某个密码当初是用哪种算法编码的。
DelegatingPasswordEncoder:委托式密码编码器
Spring Security 提供了 DelegatingPasswordEncoder 完美解决该问题。其原理是:为每种编码器分配一个唯一的标识符(例如 “bcrypt”、“scrypt”、“md5”),并将所有编码器放入一个 Map<String, PasswordEncoder>。编码时使用默认编码器,并将标识符前缀 {id} 添加到编码结果前,形成 {bcrypt}$2a$10$... 格式。校验时,从存储的字符串中提取 {id},再委托对应的编码器进行密码比对。
存储格式
{id}encodedPassword —— 其中 id 对应 Map 中的 key,后面是纯粹的单次编码结果。
例如:
{bcrypt}$2a$10$...{scrypt}$e0801$...{MD5}5d41402abc4b2a76b9719d911017c592
构造 DelegatingPasswordEncoder
以下示例中,我们设默认编码器为 bcrypt,同时保留 scrypt 和 MD5(仅用于匹配老密码)。注意 MD5 编码器需通过 new MessageDigestPasswordEncoder("MD5") 构造。
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import java.util.HashMap;
import java.util.Map;
public class PasswordEncoderConfig {
public static PasswordEncoder delegatingPasswordEncoder() {
String defaultId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put("bcrypt", new BCryptPasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
// 已弃用,仅用于兼容老数据
encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
return new DelegatingPasswordEncoder(defaultId, encoders);
}
}
将此编码器注册为 Spring Bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderConfig.delegatingPasswordEncoder();
}
}
密码匹配流程
当用户登录时,Spring Security 的 DaoAuthenticationProvider 会调用 passwordEncoder.matches(rawPassword, encodedPassword)。DelegatingPasswordEncoder 会解析 encodedPassword 中的 {id} 前缀,然后从内部 Map 获取对应的 PasswordEncoder 执行匹配。流程如下:
验证多算法共存
假设我们数据库中有两位用户:user 密码以 bcrypt 编码,zhangsan 密码以 MD5 编码。我们可以在初始化时手动构造这些密码哈希,并存入内存用户存储。
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Bean
public UserDetailsService userDetailsService(PasswordEncoder encoder) {
UserDetails user = User.builder()
.username("user")
.password("{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG")
.roles("USER")
.build();
UserDetails zhangsan = User.builder()
.username("zhangsan")
.password("{MD5}5d41402abc4b2a76b9719d911017c592") // MD5("hello")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user, zhangsan);
}
注意:{bcrypt}... 的值可以通过 encoder.encode("12345678") 提前生成,{MD5}... 可以用 new MessageDigestPasswordEncoder("MD5").encode("hello") 得到。
当用 user/12345678 或 zhangsan/hello 登录时,都能成功通过认证,说明多编码器共存工作正常。
密码升级:平滑迁移至更安全算法
当用户使用旧算法(如 MD5)成功登录后,我们有机会将其密码升级为默认的 bcrypt 编码,从而逐步淘汰不安全算法。Spring Security 的 UserDetailsPasswordService 接口提供了自动升级的钩子,但也可以手动实现:
认证成功后,Spring Security 会检查返回的 UserDetails 是否实现了 CredentialsContainer,并调用 eraseCredentials() 等方法。要触发升级,可以自定义 UserDetailsService 并在认证成功监听器中处理,或直接使用 UserDetailsPasswordService。
简化的手动升级思路:
- 用户登录成功,此时
Authentication对象中包含明文密码(调用authentication.getCredentials())。 - 判断当前密码的编码 ID 是否为
"bcrypt",若不是则调用passwordEncoder.encode(rawPassword)生成新密文。 - 将新密文更新到数据库。
Spring Security 提供了一个开箱即用的 UserDetailsPasswordService 实现 DelegatingPasswordEncoder 配合使用时,只需实现该接口并注入,即可自动升级。但为了展示核心原理,我们可以写一个简单的认证成功处理器:
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class PasswordUpgradeListener implements ApplicationListener<AuthenticationSuccessEvent> {
private final PasswordEncoder encoder;
private final UserRepository userRepository; // 假设存在
public PasswordUpgradeListener(PasswordEncoder encoder, UserRepository userRepository) {
this.encoder = encoder;
this.userRepository = userRepository;
}
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
String username = event.getAuthentication().getName();
String rawPassword = (String) event.getAuthentication().getCredentials();
String encodedPassword = userRepository.getEncodedPassword(username);
// 若当前编码器ID不是默认的bcrypt,则升级
if (encodedPassword != null && !encodedPassword.startsWith("{bcrypt}")) {
String newEncoded = encoder.encode(rawPassword);
userRepository.updatePassword(username, newEncoded);
}
}
}
使用 DelegatingPasswordEncoder 的 upgradeEncoding 方法也可以判断是否需要升级:
if (encoder.upgradeEncoding(encodedPassword)) {
String newEncoded = encoder.encode(rawPassword);
// 更新数据库
}
这样,每当老用户登录时,密码就会自动升级为安全性更高的 bcrypt 编码。
OAuth2 场景下的密码编码
在 OAuth2 授权服务器(如 Spring Authorization Server)配置中,注册的客户端通常使用 PasswordEncoder 对客户端密钥进行编码,同样可以配置 DelegatingPasswordEncoder。例如:
@Bean
public RegisteredClientRepository registeredClientRepository(PasswordEncoder encoder) {
RegisteredClient client = RegisteredClient.withId("client")
.clientId("my-client")
.clientSecret(encoder.encode("secret"))
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.scope("read")
.build();
return new InMemoryRegisteredClientRepository(client);
}
这样即便在微服务环境中存在多个授权服务或老系统数据迁移,也能保持兼容性。
完整配置示例
以下给出一个可直接运行的 Spring Boot 安全配置,整合了上述所有内容:DelegatingPasswordEncoder、多算法用户存储和表单登录。
package com.example.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
String defaultId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put("bcrypt", new BCryptPasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
return new DelegatingPasswordEncoder(defaultId, encoders);
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder encoder) {
// 预先生成的密文:{bcrypt} 对应密码 123456,{MD5} 对应密码 hello
UserDetails user1 = User.builder()
.username("user")
.password("{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG")
.roles("USER")
.build();
UserDetails user2 = User.builder()
.username("zhangsan")
.password("{MD5}5d41402abc4b2a76b9719d911017c592")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user1, user2);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.formLogin(form -> form
.defaultSuccessUrl("/home", true)
);
return http.build();
}
}
启动应用,访问 /login,分别使用 user/123456 和 zhangsan/hello 登录,均可成功认证。
总结
通过 DelegatingPasswordEncoder,Spring Security 优雅地解决了多套密码算法并存的难题,并提供了无缝的升级路径。对于长期运行的系统,这是一项不可或缺的实践。
在 OAuth2 授权服务器中,客户端密钥编码同样受益于这套机制。掌握密码编码器的配置与委托模式,将帮助开发者构建更安全、更具兼容性的认证体系。
1254



被折叠的 条评论
为什么被折叠?



