若依 Spring Security 短信,扫码登录

  1. 修改 LoginBody,添加登录类型字段

    @Data
    public class LoginBody {
    /**
    * 用户名
    */
    private String username;

     /**
      * 用户密码
      */
     private String password;
    
     /**
      * 验证码
      */
     private String code;
    
     /**
      * 唯一标识
      */
     private String uuid;
    
     /**
      * 登录类型
      */
     private String loginType;
    

    }

2.定义一个常量

package com.ruoyi.common.core.domain.constant;

/**
 * @author Ls
 * @date 2024/6/4
 */
public class LoginTypeConstant {
    public static final String PASSWORD_LOGIN = "password";
    public static final String MOBILE_LOGIN = "mobile";
    public static final String QR_CODE_LOGIN = "qrCode";
}

3.修改登录接口

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        loginBody.setLoginType(LoginTypeConstant.MOBILE_LOGIN);
        // 生成令牌
        String token = loginService.login(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

4.重载登录实现类,基本不用改,loginbody 作为 credentials传入UsernamePasswordAuthenticationToken

    public String login(LoginBody loginBody) {
        String username = loginBody.getUsername();
//        // 验证码校验
//        validateCaptcha(username, code, uuid);
//        // 登录前置校验
//        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, loginBody);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

5.自定义MyAuthenticationProvider类

package com.ruoyi.framework.security.mobile;

import com.ruoyi.common.core.domain.constant.LoginTypeConstant;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author Ls
 * @date 2024/6/4
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException, UserPasswordNotMatchException {
        String name = authentication.getName();
        LoginBody loginBody = (LoginBody) authentication.getCredentials();
        String loginType = loginBody.getLoginType();
        UserDetails user;
        switch (loginType) {
            case LoginTypeConstant.PASSWORD_LOGIN:
                user = userDetailsService.loadUserByUsername(name);
                String password = loginBody.getPassword();
                String encoderPassword = bCryptPasswordEncoder.encode(password);
                // 数据库账号密码的校验能通过就通过
                if (bCryptPasswordEncoder.matches(password, user.getPassword())) {
                    return new UsernamePasswordAuthenticationToken(user, encoderPassword);
                }
            case LoginTypeConstant.MOBILE_LOGIN:
                user = userDetailsService.loadUserByPhone(loginBody);
                return new UsernamePasswordAuthenticationToken(user, loginBody.getCode());
            case LoginTypeConstant.QR_CODE_LOGIN:
                break;
            default:
                break;
        }
        // 如果都登录不了,就返回异常输出
        throw new UserPasswordNotMatchException();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

6.用户验证类新增手机号登录 UserDetailsServiceImpl

    public UserDetails loadUserByPhone(LoginBody loginBody) throws UsernameNotFoundException {
        // TODO: 2024/6/4  各种业务效验,这里图省事验证码放在password
        if (!Objects.equals(loginBody.getPassword(), "123456")) {
            throw new ServiceException("验证码错误");
        }

        //这里应该是根据手机号查询,我这里图省事直接拿账号登录
        String username = loginBody.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        return createLoginUser(user);
    }

7.SecurityConfig调整,配置一下MyAuthenticationProvider

    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private MyAuthenticationProvider myAuthenticationProvider;


    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(myAuthenticationProvider);
    }
复制代码
相关推荐
四喜花露水9 分钟前
Vue 自定义icon组件封装SVG图标
前端·javascript·vue.js
前端Hardy18 分钟前
HTML&CSS: 实现可爱的冰墩墩
前端·javascript·css·html·css3
2401_8574396924 分钟前
SpringBoot框架在资产管理中的应用
java·spring boot·后端
怀旧66625 分钟前
spring boot 项目配置https服务
java·spring boot·后端·学习·个人开发·1024程序员节
李老头探索27 分钟前
Java面试之Java中实现多线程有几种方法
java·开发语言·面试
芒果披萨32 分钟前
Filter和Listener
java·filter
qq_49244844637 分钟前
Java实现App自动化(Appium Demo)
java
阿华的代码王国1 小时前
【SpringMVC】——Cookie和Session机制
java·后端·spring·cookie·session·会话
web Rookie1 小时前
JS类型检测大全:从零基础到高级应用
开发语言·前端·javascript
Au_ust1 小时前
css:基础
前端·css