如何在弹簧安全性中更改密码时匹配旧密码?

时间:2016-12-02 03:54:18

标签: java spring-mvc spring-security change-password

我在基于java的Web应用程序中使用spring security。我需要创建一个更改密码屏幕,用户必须输入旧密码才能确认。

我需要检查用户输入的旧密码是否与db中的旧密码匹配。

我如何在春季安全中做到这一点。

下面是我的spring security java config。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AccessDecisionManager accessDecisionManager;

    @Bean
    @Autowired
    public AccessDecisionManager accessDecisionManager(AccessDecisionVoterImpl accessDecisionVoter) {
        List<AccessDecisionVoter<?>> accessDecisionVoters = new ArrayList<AccessDecisionVoter<?>>();
        accessDecisionVoters.add(new WebExpressionVoter());
        accessDecisionVoters.add(new AuthenticatedVoter());
        accessDecisionVoters.add(accessDecisionVoter);
        UnanimousBased accessDecisionManager = new UnanimousBased(accessDecisionVoters);
        return accessDecisionManager;
    }

    @Override
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder passwordEncoder = new PasswordEncoder();
        passwordEncoder.setStringDigester(stringDigester());
        return passwordEncoder;
    }

    @Bean
    public PooledStringDigester stringDigester() {
        PooledStringDigester psd = new PooledStringDigester();

        psd.setPoolSize(2);
        psd.setAlgorithm("SHA-256");
        psd.setIterations(1000);
        psd.setSaltSizeBytes(16);
        psd.setSaltGenerator(randomSaltGenerator());

        return psd;
    }

    @Bean
    public RandomSaltGenerator randomSaltGenerator() {
        RandomSaltGenerator randomSaltGenerator = new RandomSaltGenerator();
        return randomSaltGenerator;
    }

此外,创建新用户时,我将密码设置如下。

user.setPassword(passwordUtils.encryptUserPassword(user.getPassword()));


@Component("passwordUtil")
public class PasswordUtils {

    @Autowired
    private PooledStringDigester _stringDigester;

    public String encryptUserPassword(String originalPassword) {
        String encryptedPassword = _stringDigester.digest(originalPassword);
        return encryptedPassword;
    }
}

1 个答案:

答案 0 :(得分:1)

使用用户名/电子邮件/用户ID查询存储在数据库中的密码,最后在PasswordUtils中编写一个使用PooledStringDigester.matches

的函数
public boolean isPasswordsMatch(String newPassword, String passwordFromDb) {
    return _stringDigester.matches(newPassword, passwordFromDb);
}