springsecurity中详细显示登录错误的提示信息

在spring security中,默认情况下,不管你是用户名不存在,密码错误,SS都会报出Bad credentials异常信息,而不现实具体的错误,原因是在:

DaoAuthenticationProvider的父类AbstractUserDetailsAuthenticationProvider的authenticate方法中


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;
}
}


这里有个hideUserNotFoundExceptions属性,默认是true。这样的话即便我们抛出了UsernameNotFoundException它也会转为BadCredentialsException,所以我们需要将hideUserNotFoundExceptions属性的值设为false
最后必须修改security的配置文件如下:







class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">











而在前端,则可以通过 ${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}
显示错误

你可能感兴趣的:(JAVA相关)