草庐IT

若依RuoYi整合短信验证码登录

踮脚敲代码 2023-06-16 原文

背景:若依默认使用账号密码进行登录,但是咱们客户需要增加一个短信登录功能,即在不更改原有账号密码登录的基础上,整合短信验证码登录

一、自定义短信登录 token 验证

仿照 UsernamePasswordAuthenticationToken 类,编写短信登录 token 验证。

package com.ruoyi.framework.security.authentication;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;

/**
 * 自定义短信登录token验证
 */
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    /**
     * 存储手机号码
     */
    private final Object principal;

    /**
     * 构建一个没有鉴权的构造函数
     */
    public SmsCodeAuthenticationToken(Object principal) {
        super(null);
        this.principal = principal;
        setAuthenticated(false);
    }

    /**
     * 构建一个拥有鉴权的构造函数
     */
    public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
    
}

二、编写 UserDetailsService 实现类

在用户信息库中查找出当前需要鉴权的用户,如果用户不存在,loadUserByUsername() 方法抛出异常;如果用户名存在,将用户信息和权限列表一起封装到 UserDetails 对象中。

package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author hjs
 */
@Service("userDetailsByPhonenumber")
public class UserDetailsByPhonenumberServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsByPhonenumberServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByPhonenumber(phoneNumber);
        if (StringUtils.isNull(user)) {
            log.info("登录用户:{} 不存在.", phoneNumber);
            throw new ServiceException("登录用户:" + phoneNumber+ " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户:{} 已被删除.", phoneNumber);
            throw new ServiceException("对不起,您的账号:" + phoneNumber+ " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户:{} 已被停用.", phoneNumber);
            throw new ServiceException("对不起,您的账号:" + phoneNumber+ " 已停用");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
    	return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        // return new LoginUser(user, permissionService.getMenuPermission(user));
    }

}

若你不了解创建用户(createLoginUser)的权限封装,查询用户(userService.selectUserByPhonenumber(phoneNumber))尽可能模仿账号密码登录的例子,返回对应的数据;或者在创建用户(createLoginUser)方法内加个异常捕捉;防止抛了异常没有捕捉浪费时间精力跟踪。

最近几个伙伴都在这里踩雷了,因此特显标志。

三、自定义短信登录身份认证

在 Sping Security 中因为 UserDetailsService 只提供一个根据用户名返回用户信息的动作,其他的责任跟他都没有关系,怎么将 UserDetails 组装成 Authentication 进一步向调用者返回呢?其实这个工作是由 AuthenticationProvider 完成的,下面我们自定义一个短信登录的身份鉴权。

  • 自定义一个身份认证,实现 AuthenticationProvider 接口;

  • 确定 AuthenticationProvider 仅支持短信登录类型的 Authentication 对象验证;

  • 1、重写 supports(Class<?> authentication) 方法,指定所定义的 AuthenticationProvider 仅支持短信身份验证。

  • 2、重写 authenticate(Authentication authentication) 方法,实现身份验证逻辑。

package com.ruoyi.framework.security.authentication;

import com.ruoyi.framework.security.authentication.SmsCodeAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 自定义短信登录身份认证
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public SmsCodeAuthenticationProvider(UserDetailsService userDetailsService){
        setUserDetailsService(userDetailsService);
    }
    
    /**
     * 重写 authenticate方法,实现身份验证逻辑。
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String telephone = (String) authenticationToken.getPrincipal();
        // 委托 UserDetailsService 查找系统用户
        UserDetails userDetails = userDetailsService.loadUserByUsername(telephone);
        // 鉴权成功,返回一个拥有鉴权的 AbstractAuthenticationToken
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    /**
     * 重写supports方法,指定此 AuthenticationProvider 仅支持短信验证码身份验证。
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}

四、修改 SecurityConfig 配置类

4.1 添加 bean 注入

4.2 身份认证方法加入手机登录鉴权

五、发送短信验证码

/**
 * 发送短信验证码接口
 * @param phoneNumber 手机号
 */
@ApiOperation("发送短信验证码")
@PostMapping("/sendSmsCode/{phoneNumber}")
public AjaxResult sendSmsCode(@PathVariable("phoneNumber") String phoneNumber) {
	// 手机号码
    phoneNumber = phoneNumber.trim();
    // 校验手机号
    SysUser user = sysUserService.selectUserByPhonenumber(phoneNumber);
    if (StringUtils.isNull(user)) {
        throw new ServiceException("登录用户:" + phoneNumber+ " 不存在");
    }else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
        throw new ServiceException("对不起,您的账号:" + phoneNumber+ " 已被删除");
    }else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
        throw new ServiceException("对不起,您的账号:" + phoneNumber+ " 已停用");
    }

    /**
     * 省略一千万行代码:校验发送次数,一分钟内只能发1条,一小时最多5条,一天最多10条,超出提示前端发送频率过快。
     * 登录第三方短信平台后台,康康是否可以设置短信发送频率,如果有也符合业务需求可以不做处理。
     */

    // 生成短信验证码
    String smsCode = "" + (int)((Math.random()*9+1)*1000);
    // 发送短信(实际按系统业务实现)
    SmsEntity entity = new SmsEntity(phoneNumber, smsCode);
    SendMessage.sendSms(entity);
    if(entity==null || !SmsResponseCodeEnum.SUCCESS.getCode().equals(entity.getResponseCode())){
        throw new ServiceException(entity.getResponseDesc());
    }
    // 保存redis缓存
    String uuid = IdUtils.simpleUUID();
    String verifyKey = SysConst.REDIS_KEY_SMSLOGIN_SMSCODE + uuid;
    redisCache.setCacheObject(verifyKey, smsCode, SysConst.REDIS_EXPIRATION_SMSLOGIN_SMSCODE, TimeUnit.MINUTES);

    /**
     * 省略一千万行代码:保存数据库
     */

	AjaxResult ajax = AjaxResult.success();	
	ajax.put("uuid", uuid);
    return ajax;
}

六、手机验证码登录接口

/**
 * 短信验证码登录验证
 * @param dto phoneNumber 手机号
 * @param dto smsCode 短信验证码
 * @param dto uuid 唯一标识
 */
@ApiOperation("短信验证码登录验证")
@PostMapping("/smsLogin")
public AjaxResult smsLogin(@RequestBody @Validated SmsLoginDto dto) {
	// 手机号码
    String phoneNumber = dto.getPhoneNumber();
    // 校验验证码
    String verifyKey = SysConst.REDIS_KEY_SMSLOGIN_SMSCODE + dto.getUuid();
    String captcha = redisCache.getCacheObject(verifyKey);
    if(captcha == null) {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
        // 抛出一个验证码过期异常
        throw new CaptchaExpireException();
    }
    if(!captcha.equals(dto.getSmsCode().trim())){
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
        // 抛出一个验证码错误的异常
        throw new CaptchaException();
    }
    redisCache.deleteObject(verifyKey);

    // 用户验证
    Authentication authentication = null;
    try {
        // 该方法会去调用UserDetailsByPhonenumberServiceImpl.loadUserByUsername
        authentication = authenticationManager.authenticate(new SmsCodeAuthenticationToken(phoneNumber));
    } catch (Exception e) {
        if (e instanceof BadCredentialsException) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, 
            		Constants.LOGIN_FAIL, MessageUtils.message("account.not.incorrect")));
            throw new UserPasswordNotMatchException();
        } else {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, 
            		Constants.LOGIN_FAIL, e.getMessage()));
            throw new ServiceException(e.getMessage());
        }
    }
    // 执行异步任务,记录登录信息
    AsyncManager.me().execute(AsyncFactory.recordLogininfor(phoneNumber, 
    		Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
    // 获取登录人信息
    LoginUser loginUser = (LoginUser) authentication.getPrincipal();
    // 修改最近登录IP和登录时间
    recordLoginInfo(loginUser.getUserId());
    // 生成token
    String token = tokenService.createToken(loginUser);

    // 返回token给前端
    AjaxResult ajax = AjaxResult.success();
    ajax.put(Constants.TOKEN, token);
    return ajax;
}
大功告成!创作不容易,若对您有帮助,欢迎收藏,记得赏个好评

有关若依RuoYi整合短信验证码登录的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  6. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  7. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  8. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  9. ruby-on-rails - ruby on rails 模型验证中的浮点精度 - 2

    我正在尝试使用正则表达式验证美元金额:^[0-9]+\.[0-9]{2}$这工作正常,但每当用户提交表单并且美元金额以0(零)结尾时,ruby(或rails?)将0砍掉。所以500.00变成500.0,因此正则表达式验证失败。有没有办法让ruby​​/rails保持用户输入的格式,而不管尾随零? 最佳答案 我假设您的美元金额是小数类型。因此,用户在字段中输入的任何值在保存到数据库之前都会从字符串转换为适当的类型。验证适用于已转换为数字类型的值,因此在您的情况下,正则表达式并不是真正合适的验证过滤器。不过,您有几种可能性可以解决这个问

  10. ruby-on-rails - 嵌套模型验证 - 错误不显示 - 2

    关于这个有很多问题,但似乎都没有帮助。是的,我看过thisrailscast.我有一个作者,他有很多书,像这样:作者:classAuthor书:classBook我创建了以下表单以在authors#show中向作者添加一本书:#labelsandbuttons......使用以下authors_controller方法:defshow@author=Author.find(params[:id])@book=@author.books.buildend...以及以下books_controller方法:defcreate@author=Author.find(params[:autho

随机推荐