java+vue+redis 实现token登录

使用java+redis实现用户token登录

 /**
     * 登陆
     *
     * @param loginDto
     */
    @Transactional(noRollbackFor = Exception.class)
    public JsonObjectPage login(LoginDto loginDto) throws Exception {


        // 验证码开关
        if (loginProp.isCaptchaOnOff()) {
            // 验证码校验
            validateCaptcha(loginDto.getUserid(), loginDto.getCode(), loginDto.getUuid());
        }

        TSysUser dbSysUserInfo = getUserInfoByUserId(loginDto.getUserid());

        if (Objects.isNull(dbSysUserInfo)) {
            throw new BusinessRuntimeException("用户名或密码错误");
        }

        if (dbSysUserInfo.getStatus().equals(0)) {
            throw new BusinessRuntimeException("用户状态已设置为无效,请联系管理员处理");
        }

        LoginVo loginVo = new LoginVo();

        if (loginProp.getLoginLockModel().equals(1)
                && ObjectUtil.isNotEmpty(dbSysUserInfo.getIsLock()) && dbSysUserInfo.getIsLock().equals(1)) {
            Integer loginLockTime = loginProp.getLoginLockTime();
            Date lastLoginErrTime = dbSysUserInfo.getLastLoginErrTime();
            Date dateNow = DateUtil.getDate();
            int ofSecond = DateUtil.differenceOfSecond(dateNow, lastLoginErrTime);
            if (ofSecond / 60 >= loginLockTime) {
                dbSysUserInfo.setIsLock(0);
                dbSysUserInfo.setPwdErrCount(0);
                dbSysUserInfo.setLastLoginErrTime(DateUtil.getDate());
            } else {
                throw new BusinessRuntimeException(String.format("登录失败超过%d次,账号已被锁定,请%d分钟后再试",
                        loginProp.getPwdErrLockCount(), loginProp.getLoginLockTime()));
            }
        }

        // 密码错误登录失败次数校验
        passwordCheck(loginDto, dbSysUserInfo, loginVo);

        // 是否强制修改密码
        loginVo.setIsForceModify(dbSysUserInfo.getIsForceModify());


        LogUtil.info("login 查库信息 :{}", dbSysUserInfo, log);
        if (!SecureUtils.matches(loginDto.getPassword(), dbSysUserInfo.getPassword())) {
            throw new BusinessRuntimeException("用户名或密码错误");
        }

        // 校验密码强度
        if (loginProp.getVerificationModel().equals(1)) {
//            System.out.println("login-password-check-----------:"
//                    +PasswordCheckUtil.rexCheckPassword(loginDto.getPassword())+"----:"+loginDto.getPassword());
            if (!PasswordCheckUtil.rexCheckPassword(loginDto.getPassword())) {
                loginVo.setIsForceModify(1);
                loginVo.setErrorMessage(loginProp.getCheckPasswordErrMessage());
            }
        }
//        else if (loginProp.getVerificationModel().equals(1)) {
//            if(!PasswordCheckUtil.rexCheckPassword(loginDto.getPassword())) {
//                throw new BusinessRuntimeException("密码要8位以上,大小写字母,数字,特殊字符中的至少3种");
//            }
//        }


        // 获取单位主键(organId)
        TSysUnit sysUnit = sysUnitinfoService.getUnitInfoByUnitId(dbSysUserInfo.getUnitid());
        if (Objects.isNull(sysUnit)) {
            throw new BusinessRuntimeException("用户未绑定单位信息");
        }
        // 获取用户角色
        List userRoles = roleService.listRoleByUser(String.valueOf(dbSysUserInfo.getUserid()));
        List roleInfos = userRoles.stream().map(userRole -> {
            LoginUserRoleInfo roleInfo = new LoginUserRoleInfo();
            roleInfo.setRoleid(userRole.getId());
            roleInfo.setRolename(userRole.getRolename());
            roleInfo.setRoleType(userRole.getRoleType());
            return roleInfo;
        }).collect(Collectors.toList());
        String isSysAdmin = checkLoginerRoleType(roleInfos) ? "1" : "0";

        List rolenames = userRoles.stream().map(UserRole::getRolename).collect(Collectors.toList());
        // 获取登陆用户单位的信访配置信息
        TSysUnitExp letterConfig = letterConfigService.getLetterConfig(dbSysUserInfo.getUnitid());

        String token = TokenUtil.create(String.valueOf(dbSysUserInfo.getId()), dbSysUserInfo.getUsername(), 36000);
        redisTemplate.opsForValue().set(tokenRedisKey(token), getUserInfo(dbSysUserInfo, sysUnit, token, isSysAdmin, letterConfig, rolenames), 36000, TimeUnit.SECONDS);
        loginVo.setToken(token);
        loginVo.setIsSysAdmin(isSysAdmin);
        loginVo.setUsername(dbSysUserInfo.getUsername());
        loginVo.setUserid(dbSysUserInfo.getUserid());


        loginVo.setUnitid(sysUnit.getUnitid());

        userInfoService.updateLastLogin(dbSysUserInfo);

        return JsonObjectPage.createJsonObjectPage(loginVo);
    }

TokenUtils:

public class TokenUtil {

    public static String create(String id, String subject) {
        JwtBuilder builder = Jwts.builder()
                .setId(id)        // jwt 的唯一标识,避免重放攻击
                .setSubject(subject)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, getSign());
        return builder.compact();
    }


    public static String create(String id, String subject, Integer second) {

        if (Objects.isNull(second)){
            return create(id, subject);
        }
        int millisecond = second * 1000;
        Date expir = new Date(System.currentTimeMillis() + millisecond);

        JwtBuilder builder = Jwts.builder()
                .setId(id)        // jwt 的唯一标识,避免重放攻击
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(expir)
                .signWith(SignatureAlgorithm.HS256, getSign());
        return builder.compact();
    }


    public static Claims parse(String token){
        return Jwts.parser().setSigningKey(getSign())
                .parseClaimsJws(token)
                .getBody();
    }

    public static String getSign(){
        return GlobalConstants.SIGN_KEY;
    }

 

你可能感兴趣的:(java,java,vue.js,redis)