赞
踩
1.需求
前端使用了RSA加密密码,到后端时,需要先解密,然后进行对比。
2.DaoAuthenticationProvider介绍
Spring security 获取用户信息并进行密码验证,使用的是 DaoAuthenticationProvider。
Spring Security默认的密码比对主要是依靠DaoAuthenticationProvider下的additionalAuthenticationChecks方法来完成的
下面是源码:
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
if (authentication.getCredentials() == null) {
this.logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
} else {
String presentedPassword = authentication.getCredentials().toString();
if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
this.logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
}
}
我们只需要将additionalAuthenticationChecks方法进行重写,就可以自定义密码比对业务了。
由于前台传入的是经过RSA 加密过的密码,但是数据库里面存入的又是将明文加密过的密码,所以就不能再使用Spring Security默认的密码比对方式,必须在比
对之前,先将加密的密码进行解密。
public class MyAuthenticationProvider extends DaoAuthenticationProvider {
@Resource
private PasswordEncoder passwordEncoder;
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
if (authentication.getCredentials() == null) {
this.logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
} else {
String presentedPassword = authentication.getCredentials().toString();
String decryptPassword = null;
//解密登陆密码
try {
decryptPassword=RsaUtil.decryptByPrivateKey(presentedPassword);
} catch (Exception e) {
e.printStackTrace();
}
if (!this.passwordEncoder.matches(decryptPassword, userDetails.getPassword())) {
this.logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
}
}
}
将 MyAuthenticationProvider 注入到Spring容器
@Bean
public MyAuthenticationProvider eacpsAuthenticationProvider() {
MyAuthenticationProvider myAuthenticationProvider = new MyAuthenticationProvider();
myAuthenticationProvider.setUserDetailsService(rbacUserDetailsService);
return myAuthenticationProvider;
}
需要注意的是,在注入MyAuthenticationProvider的时候,一定要记得将自己的myUserDetailService(myUserDetailService为Spring Security默认
UserDetailsService的实现类)传入到MyAuthenticationProvider中,否则将会报错,至此就全部完成了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。