项目中,使用SpringSecurity用户登录验证时,密码错误能够正常抛出异常,
但是用户不存在的情况却依然抛出密码错误的异常。
异常:总是抛出UsernameNotFoundException异常,打印出Badcredentials。
原因:hideUserNotFoundExceptions属性默认为ture,会隐藏用户不存在的异常
查看AbstractUserDetailsAuthenticationProvider的authenticate()方法
发现问题所在:hideUserNotFoundExceptions属性默认为ture
解决方案:
修改配置文件如下
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="daoAuthenticationProvider">
<!-- <sec:password-encoder ref="passwordEncoder">
<salt-source ref="saltSource"/>
</sec:password-encoder> -->
</sec:authentication-provider>
</sec:authentication-manager>
<!-- 加了这段才可以捕捉UsernameNotFoundException -->
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<!-- 必须实现的接口 -->
<property name="userDetailsService" ref="hibernateUserDetailsManager" />
<!-- 是否隐藏用户没有找到的异常,默认为true,即将不能准确地报告用户是否存在的异常 -->
<property name="hideUserNotFoundExceptions" value="false"/>
</bean>