2012-02-28 32 views
1

拋出我正在驗證我的用戶的UserDetailsS​​ervice:如何檢查BadCredentialsException不loadUserByUsername

<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指標,如果它是真的,我通過我自己的異常,反過來將用戶登錄到l oginFailureHandler(儘管密碼正確與否)我希望在loginFailureHandler中檢查是否僅在登錄成功時引發異常。

回答

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()

+0

我爲我的問題添加了更多細節。 – 2012-02-28 14:35:05

+0

@fresh_dev:如何檢查'AuthenticationSuccessHandler'中的'ForceChangePass',如果設置,則會話失效並重定向用戶更改密碼頁面?你有所有的部分('認證',請求和響應) – 2012-02-28 14:38:20

+0

好主意,謝謝 – 2012-02-28 15:35:48