我想在我的应用程序中添加用户登录验证功能。我的网站基于另一个网站,它使用复杂的哈希值来定期转换真实密码,然后将其保存到数据库中。常规创建了一个salt并将其保存到用户表,如下所示:
String salt = HashKit.generateSaltForSha256();
password = HashKit.sha256(salt + password);
user.setPassword(password).setSalt(salt).save();
当用户登录时,原始应用程序将从数据库获取salt,如下所示:
User user = dao.find(username);
password = HashKit.sha256(user.getSalt() + password);
if (password.equels(user.getPassword())){ Login Success! }
但是,现在我想使用Spring Boot重写该应用程序,并使用Spring Security验证登录,如下所示:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DruidPlugin druidPlugin;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(druidPlugin.getDataSource())
.usersByUsernameQuery(
"select userName username, password, true from account where userName=?"
)
.authoritiesByUsernameQuery(
"select userName username, 'ROLE_USER' from account where userName=?"
)
.passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence password) {
String salt = HashKit.generateSaltForSha256();
password = HashKit.sha256(salt + password);
return password.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return false;
}
});
}
}
如何从PasswordEncoder
中获取数据库中的用户数据?
我认为,DaoAuthenticationProvider
应该解决你的问题。我们需要为它提供服务实例和密码编码器。
配置完成后,我们需要将其设置为AuthenticationManagerBuilder。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
参考here