java - Spring Security 如何从 PasswordEncoder 获取用户名?
问题描述
添加新用户时,我将他的密码保存在数据库中,格式为 SHA256(cleartext_password + salt)。我为每个用户在单独的列中保存的盐值。因此,密码检查应按如下方式执行:我们从 BasicAuth 标头中提取密码明文,从数据库中获取该用户的 salt 值,执行 SHA256(cleartext_password + salt)并检查结果字符串和密码是否存储在数据库匹配。为了实现这一点,我创建了一个将执行验证的自定义 PasswordEncoder,但我无法从 PasswordEncoder 访问用户名。我需要用户名来为该用户获取盐并执行验证。我怎样才能摆脱这种情况?
这是安全性的当前实现:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService customUserDetailsService;
public SecurityConfig(UserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
.anyRequest().authenticated()
.and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService)
.passwordEncoder(new CustomPasswordEncoder());
}
}
@Component
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUserName(username);
if (user != null) {
return org.springframework.security.core.userdetails.
User.withUsername(username)
.password(new CustomPasswordEncoder().encode(user.getPassword()))
.roles("USER")
.build();
}
throw new IllegalArgumentException();
}
}
public class CustomPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String sha256hex = DigestUtils.sha256Hex(rawPassword.toString()); // Here should be DigestUtils.sha256Hex(rawPassword.toString() + salt)
return sha256hex.equals(encodedPassword);
}
}
解决方案
推荐阅读
- flutter - PetitParser 和括号
- nexus - Nexus Blobstore.compact 任务失败
- url - 如何使用 Coldfusion 从referrer 中获取值
- c++ - C++自注册工厂,多参数构造函数
- javascript - 模块导出问题,无法导出对象
- google-sheets - 如何在 Google 表格中连接和转置两个单元格范围?
- ios - 如何使用 VScode 修复 Flutter IOS 运行问题?
- ms-access - 为列表中的每个项目创建多个记录 - ACCESS
- python - 如何修改 pyinstaller 规范文件以确保数据(在这种情况下为图像)正确包含在我的最终应用程序包中?
- javascript - HTML/CSS/JavaScript/PHP - 使图像文件尽可能小