我使用UserDetailsService验证我的用户:
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="sha"/>
</authentication-provider>
</authentication-manager>
userDetailsService类:
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
User user = null;
try {
user = userService.getUserByUsername(username);
} catch (Exception e) {
e.printStackTrace();
}
if (user.isForceChangePass()) {
MyForcePasswordChangeException bad = new MyForcePasswordChangeException(
"Password is not valid, and it must be changed!");
throw bad;
}
}
修改
获取用户名后我检查ForceChangePass指标,如果它是真的我通过我自己的异常反过来将用户登陆到loginFailureHandler(尽管密码是否正确)我想在loginFailureHandler中检查我的异常是否被抛出以防万一仅登录成功。
答案 0 :(得分:2)
loadUserByUsername()
不会检查凭据,它只应加载UserDetails
对象(使用getPassword()
方法)或抛出UsernameNotFoundException
。
如果您想检查用户是否成功通过身份验证,请查看Listening to successful login with Spring Security:
<form-login
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-url="authenticationFailureHandler"/>
您必须实施AuthenticationSuccessHandler
和AuthenticationFailureHandler
。
或者考虑继承BasicAuthenticationFilter
并覆盖onSuccessfulAuthentication()
和onUnsuccessfulAuthentication()
。