对于Springsecurity的密码验证机制的深入探究
最近在做Spring Security的授权认证
做完之后再进行登陆操作时出现了这样的错误
“Encoded password does not look like BCrypt”
这个错误刚出来的时候我是很懵的,毕竟这个所谓的Encoded password 究竟在哪里?只能硬着头皮去查源码,在
DaoAuthenticationProvider文件中可以发现如下代码。
String presentedPassword = authentication.getCredentials().toString();
//这里是验证密码正确的关键步骤
if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
这里的presentedPassword是经由前端发送的明文密码,后面的则是由该类调用的函数经过数据库操作之后返回的传送过来的userDetails对象,于是接着看一下passwordEncoder.matches()这个函数
boolean matches(CharSequence rawPassword, String encodedPassword);
/**
* Returns true if the encoded password should be encoded again for better security,
* else false. The default implementation always returns false.
* @param encodedPassword the encoded password to check
* @return true if the encoded password should be encoded again for better security,
* else false.
*/
这是有关该方法的注释,可以看到第一个参数是未加密的密码,第二个参数是加密后的密码
我所用的加密方法是BCryptPasswordEncoder,因此直接找到这个类看他的实现如何。
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (rawPassword == null) {
throw new IllegalArgumentException("rawPassword cannot be null");
}
if (encodedPassword == null || encodedPassword.length() == 0) {
logger.warn("Empty encoded password");
return false;
}
if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
logger.warn("Encoded password does not look like BCrypt");
return false;
}
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
发现了错误代码的提示,这就意味着我存在数据库里的信息不能够是未加密后的密码,必须是经过加密后的密码,在数据库中插入几条信息,密码在加密后再存进去,问题得以解决
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/17792.html