如何检查loadUserByUsername中是否未引发BadCredentialsException

时间:2012-02-28 12:59:39

标签: spring spring-security

我使用UserDetailsS​​ervice验证我的用户:

<authentication-manager alias="authenticationManager">          
      <authentication-provider user-service-ref="userDetailsService">
         <password-encoder hash="sha"/>             
      </authentication-provider>   
    </authentication-manager> 

userDetailsS​​ervice类:

@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中检查我的异常是否被抛出以防万一仅登录成功。

1 个答案:

答案 0 :(得分:2)

loadUserByUsername()不会检查凭据,它只应加载UserDetails对象(使用getPassword()方法)或抛出UsernameNotFoundException

如果您想检查用户是否成功通过身份验证,请查看Listening to successful login with Spring Security

<form-login 
  authentication-success-handler-ref="authenticationSuccessHandler"
  authentication-failure-url="authenticationFailureHandler"/>

您必须实施AuthenticationSuccessHandlerAuthenticationFailureHandler

或者考虑继承BasicAuthenticationFilter并覆盖onSuccessfulAuthentication()onUnsuccessfulAuthentication()