遇到一个场景,需要同时支持手机号或者邮箱和密码或者验证码进行登录的场景,故来记录一下。
说明:此流程主要是基于若依框架集成的多种方式登录,主要演示登录业务逻辑和前端登录密码和验证码切换组件和配置Security
一:后端登录业务逻辑代码:
因为有多个端,多个语言共享登录接口,所以,接口定义尽量简单,接口内的逻辑判断尽量全面,判断手机号还是邮箱登录,再判断密码还是验证码登录,验证完了之后,再去验证用户是否存在数据库中,如果是密码登录的,则需要对比密码,然后再创建一个登录的token,返回。
public AjaxResult login(LoginBody loginBody){
//验证手机号和邮箱是否符合格式或者是否为空
boolean isPhone = false;
//先判断是手机号还是邮箱登录
if(StringUtils.isNotEmpty(loginBody.getTel()) && Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$").matcher(loginBody.getTel()).matches()){
isPhone = true;
}else if(StringUtils.isNotEmpty(loginBody.getEmail()) && loginBody.getEmail().matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2}")){
isPhone = false;
}else{
return AjaxResult.error("登录失败,邮箱和手机号不能同时为空!");
}
//在判断是密码还是验证码登录
boolean isPassword = false;
if(StringUtils.isNotEmpty(loginBody.getPassword())){
isPassword = true;
}else if(StringUtils.isNotEmpty(loginBody.getCode())){
isPassword = false;
}else{
return AjaxResult.error("登录失败,密码和验证码不能同时为空!");
}
//验证码验证
if(!isPassword){
String codeKey = "0:" + isPhone? loginBody.getTel(): loginBody.getEmail());
String value = redisCache.getCacheObject(codeKey);
if (StringUtils.isNotEmpty(value)) {
if (!value.equals(loginBody.getCode())) {
return AjaxResult.error("验证码错误!");
}
}else{
return AjaxResult.error("验证码超时!");
}
}
// 用户验证
Authentication authentication = null;
try
{
if(isPassword){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(isPhone? loginBody.getTel(): loginBody.getEmail(), loginBody.getPassword());
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}else{
// 该方法会去调用UsernamePhoneUserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(new UsernamePhoneAuthenticationToken(isPhone? loginBody.getTel

本文介绍了如何在系统中实现支持手机号或邮箱,以及密码或验证码的登录方式。后端通过验证手机号或邮箱格式,以及密码或验证码,结合SpringSecurity进行用户认证。前端使用Vue.js组件展示登录表单,动态切换密码和验证码输入。同时,文章提到了自定义AuthenticationToken和UserDetailsService来处理不同类型的登录验证。
最低0.47元/天 解锁文章
1439





