spring安全如何从passwordencoder获取用户名?

zf2sa74q  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(308)

添加新用户时,我将其密码保存在数据库中,格式为sha256(明文密码+salt)。我将盐值保存在每个用户的单独列中。相应地,密码检查应按如下方式执行:我们从basicauth头中提取密码明文,从数据库中获取此用户的salt值,执行sha256(cleartext_password+salt),并检查结果字符串和存储在数据库中的密码是否匹配。为了实现这一点,我需要创建一个自定义的passwordencoder来执行验证,但是我不能从passwordencoder访问用户名。我需要用户名为该用户获取salt并执行验证。我怎样才能摆脱这种局面?
以下是安全性的当前实现:

@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);
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题