1. 程式人生 > >Spring Security實現使用者名稱或者手機號登入

Spring Security實現使用者名稱或者手機號登入

使用Spring Security來管理web專案的使用者許可權,是很多Java管理系統經常使用的方法。
然而,當前很多網站都支援使用手機號+密碼登入網站。畢竟,使用者名稱這個東西肯定沒有自己的手機號好記。

Spring Security許可權管理

Spring Security主要分為認證(Authentication),授權(Authorization)兩大模組:

簡而言之,鑑權就是鑑定使用者“是誰”,而授權則是鑑定使用者“是否可以”做這件事情或訪問某個URL。當然授權的前提是明確知道當前的使用者“是誰”,所以一般情況下鑑權發生在授權之前。

使用使用者名稱或者手機號登入

使用Spring Security時,我們一般需要實現一個UserDetailsService介面:
UserDetailsService
這個介面只有一個方法需要重寫:
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

Locates the user based on the username. In the actual implementation, the search may possibly be case sensitive, or case insensitive depending on how the implementation instance is configured. In this case, the UserDetails object that comes back may have a username that is of a different case than what was actually requested..

根據方法名就可以知道,Spring Security是通過這個方法來驗證使用者名稱是否存在。那麼,我們只需要在這個方法中,加入手機號查詢的邏輯即可。

public UserDetails loadUserByUsername(String ssoId) throws UsernameNotFoundException {
    User ssoIdUser = userService.findBySSO(ssoId);
    if (ssoIdUser == null) {
        User mobileUser = userService.findByMobile(ssoId);
        if
(mobileUser == null) { throw new UsernameNotFoundException("Username not found"); } else { return new org.springframework.security.core.userdetails.User(mobileUser.getSsoId(), mobileUser.getPassword(), true, true, true, true, getGrantedAuthorities(mobileUser)); } } else { return new org.springframework.security.core.userdetails.User(ssoIdUser.getSsoId(), ssoIdUser.getPassword(), true, true, true, true, getGrantedAuthorities(ssoIdUser)); } }

注意點

在使用者名稱-密碼登入中,我們需要保證使用者名稱唯一性。因此,在增加手機號登入之後,我們需要在建立使用者時,需要保證:

  1. 使用者名稱跟已存在的使用者名稱和已存在的手機號不能重複;
  2. 手機號跟已存在的使用者名稱和已存在的手機號不能重複。

後續工作

既然實現了同時支援使用者名稱手機號登入,那麼肯定會涉及到現在流行的直接使用手機驗證碼登入了。
畢竟,記密碼真是個煩人的事情。
後面,我會再寫一篇基於Spring Security實現手機驗證碼登入的部落格。

參考