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实现手机验证码登录的博客。

参考

深入了解 Spring Security

猜你喜欢

转载自blog.csdn.net/jiangshanwe/article/details/73656034