springSecurity 中不能抛出异常UserNameNotFoundException 解析

3次阅读

共计 4713 个字符,预计需要花费 12 分钟才能阅读完成。

通过查看源码可得知:
1. 前言
抽象类中 AbstractUserDetailsAuthenticationProvider 接口抛出异常 AuthenticationException
下面源码注释这么描述
*
* @throws AuthenticationException if the credentials could not be validated
* (generally a <code>BadCredentialsException</code>, an
* <code>AuthenticationServiceException</code> or
* <code>UsernameNotFoundException</code>)
*/
protected abstract UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException;
AuthenticationException 抛出的情况是 BadCredentialsException,AuthenticationServiceException,UsernameNotFoundException 这三个异常。
当 UserNameNotFoundException 这个异常的情况下会抛出
可实际情况下我们 查询的 user 为 null 抛出了 UserNameNotFoundException 这个异常但是实际并没有抛出来,抛出的是 AuthenticationException
通过继续往下查看源码后明白了,原来是做了对 UserNameNotFoundException 处理,转换成了 AuthenticationException 这个异常;
hideUserNotFoundExceptions = true;

boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(username);

if (user == null) {
cacheWasUsed = false;

try {
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (UsernameNotFoundException notFound) {
logger.debug(“User ‘” + username + “‘ not found”);

if (hideUserNotFoundExceptions) {
throw new BadCredentialsException(messages.getMessage(
“AbstractUserDetailsAuthenticationProvider.badCredentials”,
“Bad credentials”));
}
else {
throw notFound;
}
}
所以我们没有抛出 UsernameNotFoundException 这个异常, 而是将这个异常进行了转换。
2. 解决办法
如何抛出这个异常,那就是将 hideUserNotFoundExceptions 设置为 false;
2.1 设置实现类中
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(mUserDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
最后在 WebSecurityConfig 配置即可
auth.authenticationProvider(daoAuthenticationProvider());
2.2 debug 来看一下
设置之前设置之后
抛出的 UsernameNotFoundException 异常已经捕获到了,然后进入 if 中最后抛出
new BadCredentialsException(messages.getMessage(
“AbstractUserDetailsAuthenticationProvider.badCredentials”,
“Bad credentials”))
会将异常信息存入 session 中,根据 key 即可获取最后在失败的处理器中获取到
@Component
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

public MyAuthenctiationFailureHandler() {
this.setDefaultFailureUrl(“/loginPage”);
}

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
logger.info(“ 进入认证失败处理类 ”);
HttpSession session = request.getSession();
AuthenticationException attributes = (AuthenticationException) session.getAttribute(“SPRING_SECURITY_LAST_EXCEPTION”);
logger.info(“aaaa ” + attributes);
super.onAuthenticationFailure(request, response, exception);
}
}

这样子做可以直接在 session 中获取到,如果自定义抛出一个异常首先控制台会报异常错,其次前台的通过如 ajax 获取错误信息,又得写 ajax。
这样子做直接将信息存入 session 中,springSecurity 直接为我们封装到 session 中了,可以直接根据 key 获取到。
如:${session.SPRING_SECURITY_LAST_EXCEPTION.message}

2.4 判断密码
注意 如果用户名不存在,抛了异常
不要再在密码验证其中抛出密码错误异常,不然抛出 UserNameNotFoundException 后还会验证密码是否正确,如果密码正确还好,返回 true,如果不正确抛出异常。此时会将 UsernameNotFoundException 异常覆盖,这里应该返回 false。
源码如下:
protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
prepareTimingAttackProtection();
try {
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
“UserDetailsService returned null, which is an interface contract violation”);
}
return loadedUser;
}
catch (UsernameNotFoundException ex) {
//、、、、、、、这里会去匹配密码是否正确
mitigateAgainstTimingAttack(authentication);
throw ex;
}
catch (InternalAuthenticationServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
}
}
mitigateAgainstTimingAttack 方法
private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
if (authentication.getCredentials() != null) {
String presentedPassword = authentication.getCredentials().toString();
// 这里会是自定义密码加密
this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
}
}

我的密码加密器
@Override
public boolean matches(CharSequence charSequence, String s) {

String pwd = charSequence.toString();
log.info(“ 前端传过来密码为:” + pwd);
log.info(“ 加密后密码为:” + MD5Util.encode(charSequence.toString()));
log.info(“ 数据库存储的密码:” + s);
//s 应在数据库中加密
if(MD5Util.encode(charSequence.toString()).equals(MD5Util.encode(s))){
return true;
}

//throw new DisabledException(“– 密码错误 –“); // 不能抛出异常
return false;
}
如下是 我们密码验证器里抛出异常后获取到的异常
异常
密码未验证 之前捕获到的异常信息验证密码后捕获到的异常 (这里跳到 ProviderManager 中)
既然我用户名不对我就不必要验证密码了,所以不应该抛出异常,应该直接返回 false。不然。此处密码异常会将 用户不存在进行覆盖!
3. 验证页面代码
<body>
登录页面
<div th:text=”${session.SPRING_SECURITY_LAST_EXCEPTION!=null?session.SPRING_SECURITY_LAST_EXCEPTION.message:”}”>[…]</div>
<form method=”post” action=”/login” >
<input type=”text” name=”username” /><br>
<input type=”password” name=”password” />

<input type=”submit” value=”login” />

</form>

正文完
 0