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

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值