以下配置基于spring boot版本1.4.2.RELEASE,默认引入的spring security版本为4.1.3.RELEASE,页面模板采用thymeleaf。
在MyUserDetailsService实现了UserDetailsService接口以后,在重写的loadUserByUsername方法里验证用户名不存在时,我们会抛出一个UsernameNotFoundException异常,比如:
throw new UsernameNotFoundException(“用户名不存在”);
但是返回页面以后, 发现并不能捕获这个异常信息,通过[[${session.SPRING_SECURITY_LAST_EXCEPTION.message}]]方式获得的异常信息始终是“Bad credentials”。
通过程序调试发现,系统在执行到throw new UsernameNotFoundException(“用户名不存在”)的时候,会执行DaoAuthenticationProvider类的retrieveUser方法:
protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
.............................
catch (UsernameNotFoundException notFound) {
if (authentication.getCredentials() != null) {
String presentedPassword = authentication.getCredentials().toString();
passwordEncoder.isPasswordValid(userNotFoundEncodedPassword,

在Spring Boot 1.4.2.RELEASE与Spring Security 4.1.3.RELEASE集成时,遇到UsernameNotFoundException无法被捕获的问题。系统在 DaoAuthenticationProvider 的 retrieveUser 方法中捕获该异常并转换为 BadCredentialsException。文章提供了两种解决方案:1) 创建自定义异常 MyUsernameNotFoundException 并在 loadUserByUsername 方法中抛出;2) 直接在 loadUserByUsername 方法中抛出 BadCredentialsException 异常。
最低0.47元/天 解锁文章
5万+

被折叠的 条评论
为什么被折叠?



