Java Code Examples for org.jeecg.common.system.util.JwtUtil

The following examples show how to use org.jeecg.common.system.util.JwtUtil. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jeecg-cloud   Source File: ShiroRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * JWTToken刷新生命周期 (实现: 用户在线操作不掉线功能)
	 * 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样),缓存有效期设置为Jwt有效时间的2倍
	 * 2、当该用户再次请求时,通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证
	 * 3、当该用户这次请求jwt生成的token值已经超时,但该token对应cache中的k还是存在,则表示该用户一直在操作只是JWT的token失效了,程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值,该缓存生命周期重新计算
	 * 4、当该用户这次请求jwt在生成的token值已经超时,并在cache中不存在对应的k,则表示该用户账户空闲超时,返回用户信息已失效,请重新登录。
	 * 注意: 前端请求Header中设置Authorization保持不变,校验有效性以缓存中的token为准。
     *       用户过期时间 = Jwt有效时间 * 2。
	 *
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public boolean jwtTokenRefresh(String token, String userName, String passWord) {
		String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
		if (oConvertUtils.isNotEmpty(cacheToken)) {
			// 校验token有效性
			if (!JwtUtil.verify(cacheToken, userName, passWord)) {
				String newAuthorization = JwtUtil.sign(userName, passWord);
				// 设置超时时间
				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
                log.info("——————————用户在线操作,更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
			}
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//			else {
//				// 设置超时时间
//				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//			}
            //update-end--Author:scott  Date:20191005   for:解决每次请求,都重写redis中 token缓存问题
			return true;
		}
		return false;
	}
 
Example 2
Source Project: jeecg-cloud   Source File: SysDepartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
//@RequiresRoles({"admin"})
@RequestMapping(value = "/add", method = RequestMethod.POST)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	Result<SysDepart> result = new Result<SysDepart>();
	String username = JwtUtil.getUserNameByToken(request);
	try {
		sysDepart.setCreateBy(username);
		sysDepartService.saveDepartData(sysDepart, username);
		//清除部门树内存
		// FindsDepartsChildrenUtil.clearSysDepartTreeList();
		// FindsDepartsChildrenUtil.clearDepartIdModel();
		result.success("添加成功!");
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		result.error500("操作失败");
	}
	return result;
}
 
Example 3
Source Project: jeecg-cloud   Source File: SysDepartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 编辑数据 编辑部门的部分数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
//@RequiresRoles({"admin"})
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	String username = JwtUtil.getUserNameByToken(request);
	sysDepart.setUpdateBy(username);
	Result<SysDepart> result = new Result<SysDepart>();
	SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
	if (sysDepartEntity == null) {
		result.error500("未找到对应实体");
	} else {
		boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
		// TODO 返回false说明什么?
		if (ok) {
			//清除部门树内存
			//FindsDepartsChildrenUtil.clearSysDepartTreeList();
			//FindsDepartsChildrenUtil.clearDepartIdModel();
			result.success("修改成功!");
		}
	}
	return result;
}
 
Example 4
Source Project: jeecg-cloud   Source File: ThirdLoginController.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@RequestMapping(value = "/getLoginUser/{token}", method = RequestMethod.GET)
@ResponseBody
public Result<JSONObject> getLoginUser(@PathVariable("token") String token) throws Exception {
	Result<JSONObject> result = new Result<JSONObject>();
	String username = JwtUtil.getUsername(token);
	
	//1. 校验用户是否有效
	SysUser sysUser = sysUserService.getUserByName(username);
	result = sysUserService.checkUserIsEffective(sysUser);
	if(!result.isSuccess()) {
		return result;
	}
	JSONObject obj = new JSONObject();
	//用户登录信息
	obj.put("userInfo", sysUser);
	//token 信息
	obj.put("token", token);
	result.setResult(obj);
	result.setSuccess(true);
	result.setCode(200);
	sysBaseAPI.addLog("用户名: " + username + ",登录成功[第三方用户]!", CommonConstant.LOG_TYPE_1, null);
	return result;
}
 
Example 5
Source Project: jeecg-cloud   Source File: TokenUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * 刷新token(保证用户在线操作不掉线)
     * @param token
     * @param userName
     * @param passWord
     * @param redisUtil
     * @return
     */
    private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
        String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
        if (oConvertUtils.isNotEmpty(cacheToken)) {
            // 校验token有效性
            if (!JwtUtil.verify(cacheToken, userName, passWord)) {
                String newAuthorization = JwtUtil.sign(userName, passWord);
                // 设置Toekn缓存有效时间
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
            }
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//            else {
//                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//                // 设置超时时间
//                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//            }
            //update-end--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
            return true;
        }
        return false;
    }
 
Example 6
Source Project: jeecg-boot-with-activiti   Source File: TokenUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 验证Token
 */
public static boolean verifyToken(HttpServletRequest request, ISysBaseAPI sysBaseAPI, RedisUtil redisUtil) {
    String token = request.getParameter("token");

    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);
    if (username == null) {
        throw new AuthenticationException("token非法无效!");
    }

    // 查询用户信息
    LoginUser user = sysBaseAPI.getUserByName(username);
    if (user == null) {
        throw new AuthenticationException("用户不存在!");
    }
    // 判断用户状态
    if (user.getStatus() != 1) {
        throw new AuthenticationException("账号已被锁定,请联系管理员!");
    }
    // 校验token是否超时失效 & 或者账号密码是否错误
    if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
        throw new AuthenticationException("Token失效,请重新登录!");
    }
    return true;
}
 
Example 7
Source Project: jeecg-boot-with-activiti   Source File: TokenUtils.java    License: MIT License 6 votes vote down vote up
/**
     * 刷新token(保证用户在线操作不掉线)
     * @param token
     * @param userName
     * @param passWord
     * @param redisUtil
     * @return
     */
    private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
        String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
        if (oConvertUtils.isNotEmpty(cacheToken)) {
            // 校验token有效性
            if (!JwtUtil.verify(cacheToken, userName, passWord)) {
                String newAuthorization = JwtUtil.sign(userName, passWord);
                // 设置Toekn缓存有效时间
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
            }
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//            else {
//                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//                // 设置超时时间
//                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//            }
            //update-end--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
            return true;
        }
        return false;
    }
 
Example 8
Source Project: jeecg-boot-with-activiti   Source File: ShiroRealm.java    License: MIT License 6 votes vote down vote up
/**
 * 校验token的有效性
 *
 * @param token
 */
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
	// 解密获得username,用于和数据库进行对比
	String username = JwtUtil.getUsername(token);
	if (username == null) {
		throw new AuthenticationException("token非法无效!");
	}

	// 查询用户信息
	log.info("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
       LoginUser loginUser = sysBaseAPI.getUserByName(username);
	if (loginUser == null) {
		throw new AuthenticationException("用户不存在!");
	}
       // 判断用户状态
       if (loginUser.getStatus() != 1) {
           throw new AuthenticationException("账号已被锁定,请联系管理员!");
       }
	// 校验token是否超时失效 & 或者账号密码是否错误
	if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
		throw new AuthenticationException("Token失效,请重新登录!");
	}

	return loginUser;
}
 
Example 9
Source Project: jeecg-boot-with-activiti   Source File: ShiroRealm.java    License: MIT License 6 votes vote down vote up
/**
	 * JWTToken刷新生命周期 (实现: 用户在线操作不掉线功能)
	 * 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样),缓存有效期设置为Jwt有效时间的2倍
	 * 2、当该用户再次请求时,通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证
	 * 3、当该用户这次请求jwt生成的token值已经超时,但该token对应cache中的k还是存在,则表示该用户一直在操作只是JWT的token失效了,程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值,该缓存生命周期重新计算
	 * 4、当该用户这次请求jwt在生成的token值已经超时,并在cache中不存在对应的k,则表示该用户账户空闲超时,返回用户信息已失效,请重新登录。
	 * 注意: 前端请求Header中设置Authorization保持不变,校验有效性以缓存中的token为准。
     *       用户过期时间 = Jwt有效时间 * 2。
	 *
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public boolean jwtTokenRefresh(String token, String userName, String passWord) {
		String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
		if (oConvertUtils.isNotEmpty(cacheToken)) {
			// 校验token有效性
			if (!JwtUtil.verify(cacheToken, userName, passWord)) {
				String newAuthorization = JwtUtil.sign(userName, passWord);
				// 设置超时时间
				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
                log.info("——————————用户在线操作,更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
			}
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//			else {
//				// 设置超时时间
//				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//			}
            //update-end--Author:scott  Date:20191005   for:解决每次请求,都重写redis中 token缓存问题
			return true;
		}
		return false;
	}
 
Example 10
Source Project: jeecg-boot-with-activiti   Source File: SysDepartController.java    License: MIT License 6 votes vote down vote up
/**
 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	Result<SysDepart> result = new Result<SysDepart>();
	String username = JwtUtil.getUserNameByToken(request);
	try {
		sysDepart.setCreateBy(username);
		sysDepartService.saveDepartData(sysDepart, username);
		//清除部门树内存
		// FindsDepartsChildrenUtil.clearSysDepartTreeList();
		// FindsDepartsChildrenUtil.clearDepartIdModel();
		result.success("添加成功!");
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		result.error500("操作失败");
	}
	return result;
}
 
Example 11
Source Project: jeecg-boot-with-activiti   Source File: SysDepartController.java    License: MIT License 6 votes vote down vote up
/**
 * 编辑数据 编辑部门的部分数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	String username = JwtUtil.getUserNameByToken(request);
	sysDepart.setUpdateBy(username);
	Result<SysDepart> result = new Result<SysDepart>();
	SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
	if (sysDepartEntity == null) {
		result.error500("未找到对应实体");
	} else {
		boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
		// TODO 返回false说明什么?
		if (ok) {
			//清除部门树内存
			//FindsDepartsChildrenUtil.clearSysDepartTreeList();
			//FindsDepartsChildrenUtil.clearDepartIdModel();
			result.success("修改成功!");
		}
	}
	return result;
}
 
Example 12
Source Project: jeecg-boot-with-activiti   Source File: LoginController.java    License: MIT License 6 votes vote down vote up
/**
 * 退出登录
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/logout")
public Result<Object> logout(HttpServletRequest request,HttpServletResponse response) {
	//用户退出逻辑
    String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
    if(oConvertUtils.isEmpty(token)) {
    	return Result.error("退出登录失败!");
    }
    String username = JwtUtil.getUsername(token);
	LoginUser sysUser = sysBaseAPI.getUserByName(username);
    if(sysUser!=null) {
    	sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功!", CommonConstant.LOG_TYPE_1, null);
    	log.info(" 用户名:  "+sysUser.getRealname()+",退出成功! ");
    	//清空用户登录Token缓存
    	redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
    	//清空用户登录Shiro权限缓存
    	redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
    	return Result.ok("退出登录成功!");
    }else {
    	return Result.error("Token无效!");
    }
}
 
Example 13
Source Project: teaching   Source File: TokenUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * 刷新token(保证用户在线操作不掉线)
     * @param token
     * @param userName
     * @param passWord
     * @param redisUtil
     * @return
     */
    private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
        String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
        if (oConvertUtils.isNotEmpty(cacheToken)) {
            // 校验token有效性
            if (!JwtUtil.verify(cacheToken, userName, passWord)) {
                String newAuthorization = JwtUtil.sign(userName, passWord);
                // 设置Toekn缓存有效时间
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
            }
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//            else {
//                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//                // 设置超时时间
//                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//            }
            //update-end--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
            return true;
        }
        return false;
    }
 
Example 14
Source Project: teaching   Source File: ShiroRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 校验token的有效性
 *
 * @param token
 */
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
	// 解密获得username,用于和数据库进行对比
	String username = JwtUtil.getUsername(token);
	if (username == null) {
		throw new AuthenticationException("token非法无效!");
	}

	// 查询用户信息
	log.info("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
       LoginUser loginUser = sysBaseAPI.getUserByName(username);
	if (loginUser == null) {
		throw new AuthenticationException("用户不存在!");
	}
       // 判断用户状态
       if (loginUser.getStatus() != 1) {
           throw new AuthenticationException("账号已被锁定,请联系管理员!");
       }
	// 校验token是否超时失效 & 或者账号密码是否错误
	if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
		throw new AuthenticationException("Token失效,请重新登录!");
	}

	return loginUser;
}
 
Example 15
Source Project: teaching   Source File: ShiroRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * JWTToken刷新生命周期 (实现: 用户在线操作不掉线功能)
	 * 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样),缓存有效期设置为Jwt有效时间的2倍
	 * 2、当该用户再次请求时,通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证
	 * 3、当该用户这次请求jwt生成的token值已经超时,但该token对应cache中的k还是存在,则表示该用户一直在操作只是JWT的token失效了,程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值,该缓存生命周期重新计算
	 * 4、当该用户这次请求jwt在生成的token值已经超时,并在cache中不存在对应的k,则表示该用户账户空闲超时,返回用户信息已失效,请重新登录。
	 * 注意: 前端请求Header中设置Authorization保持不变,校验有效性以缓存中的token为准。
     *       用户过期时间 = Jwt有效时间 * 2。
	 *
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public boolean jwtTokenRefresh(String token, String userName, String passWord) {
		String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
		if (oConvertUtils.isNotEmpty(cacheToken)) {
			// 校验token有效性
			if (!JwtUtil.verify(cacheToken, userName, passWord)) {
				String newAuthorization = JwtUtil.sign(userName, passWord);
				// 设置超时时间
				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
                log.info("——————————用户在线操作,更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
			}
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//			else {
//				// 设置超时时间
//				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//			}
            //update-end--Author:scott  Date:20191005   for:解决每次请求,都重写redis中 token缓存问题
			return true;
		}
		return false;
	}
 
Example 16
Source Project: teaching   Source File: SysDepartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	Result<SysDepart> result = new Result<SysDepart>();
	String username = JwtUtil.getUserNameByToken(request);
	try {
		sysDepart.setCreateBy(username);
		sysDepartService.saveDepartData(sysDepart, username);
		//清除部门树内存
		// FindsDepartsChildrenUtil.clearSysDepartTreeList();
		// FindsDepartsChildrenUtil.clearDepartIdModel();
		result.success("添加成功!");
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		result.error500("操作失败");
	}
	return result;
}
 
Example 17
Source Project: teaching   Source File: SysDepartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 编辑数据 编辑部门的部分数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	String username = JwtUtil.getUserNameByToken(request);
	sysDepart.setUpdateBy(username);
	Result<SysDepart> result = new Result<SysDepart>();
	SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
	if (sysDepartEntity == null) {
		result.error500("未找到对应实体");
	} else {
		boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
		// TODO 返回false说明什么?
		if (ok) {
			//清除部门树内存
			//FindsDepartsChildrenUtil.clearSysDepartTreeList();
			//FindsDepartsChildrenUtil.clearDepartIdModel();
			result.success("修改成功!");
		}
	}
	return result;
}
 
Example 18
Source Project: teaching   Source File: LoginController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 退出登录
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/logout")
public Result<Object> logout(HttpServletRequest request,HttpServletResponse response) {
	//用户退出逻辑
    String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
    if(oConvertUtils.isEmpty(token)) {
    	return Result.error("退出登录失败!");
    }
    String username = JwtUtil.getUsername(token);
	LoginUser sysUser = sysBaseAPI.getUserByName(username);
    if(sysUser!=null) {
    	sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功!", CommonConstant.LOG_TYPE_1, null);
    	log.info(" 用户名:  "+sysUser.getRealname()+",退出成功! ");
    	//清空用户登录Token缓存
    	redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
    	//清空用户登录Shiro权限缓存
		redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
		//清空用户的缓存信息(包括部门信息),例如sys:cache:user::<username>
		redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
		//调用shiro的logout
		SecurityUtils.getSubject().logout();
    	return Result.ok("退出登录成功!");
    }else {
    	return Result.error("Token无效!");
    }
}
 
Example 19
Source Project: jeecg-boot   Source File: TokenUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * 刷新token(保证用户在线操作不掉线)
     * @param token
     * @param userName
     * @param passWord
     * @param redisUtil
     * @return
     */
    private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
        String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
        if (oConvertUtils.isNotEmpty(cacheToken)) {
            // 校验token有效性
            if (!JwtUtil.verify(cacheToken, userName, passWord)) {
                String newAuthorization = JwtUtil.sign(userName, passWord);
                // 设置Toekn缓存有效时间
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
            }
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//            else {
//                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//                // 设置超时时间
//                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//            }
            //update-end--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
            return true;
        }
        return false;
    }
 
Example 20
Source Project: jeecg-boot   Source File: ShiroRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 校验token的有效性
 *
 * @param token
 */
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
	// 解密获得username,用于和数据库进行对比
	String username = JwtUtil.getUsername(token);
	if (username == null) {
		throw new AuthenticationException("token非法无效!");
	}

	// 查询用户信息
	log.debug("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
       LoginUser loginUser = sysBaseAPI.getUserByName(username);
	if (loginUser == null) {
		throw new AuthenticationException("用户不存在!");
	}
       // 判断用户状态
       if (loginUser.getStatus() != 1) {
           throw new AuthenticationException("账号已被锁定,请联系管理员!");
       }
	// 校验token是否超时失效 & 或者账号密码是否错误
	if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
		throw new AuthenticationException("Token失效,请重新登录!");
	}

	return loginUser;
}
 
Example 21
Source Project: jeecg-boot   Source File: ShiroRealm.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * JWTToken刷新生命周期 (实现: 用户在线操作不掉线功能)
	 * 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样),缓存有效期设置为Jwt有效时间的2倍
	 * 2、当该用户再次请求时,通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证
	 * 3、当该用户这次请求jwt生成的token值已经超时,但该token对应cache中的k还是存在,则表示该用户一直在操作只是JWT的token失效了,程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值,该缓存生命周期重新计算
	 * 4、当该用户这次请求jwt在生成的token值已经超时,并在cache中不存在对应的k,则表示该用户账户空闲超时,返回用户信息已失效,请重新登录。
	 * 注意: 前端请求Header中设置Authorization保持不变,校验有效性以缓存中的token为准。
     *       用户过期时间 = Jwt有效时间 * 2。
	 *
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public boolean jwtTokenRefresh(String token, String userName, String passWord) {
		String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
		if (oConvertUtils.isNotEmpty(cacheToken)) {
			// 校验token有效性
			if (!JwtUtil.verify(cacheToken, userName, passWord)) {
				String newAuthorization = JwtUtil.sign(userName, passWord);
				// 设置超时时间
				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
                log.info("——————————用户在线操作,更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
			}
            //update-begin--Author:scott  Date:20191005  for:解决每次请求,都重写redis中 token缓存问题
//			else {
//				// 设置超时时间
//				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//			}
            //update-end--Author:scott  Date:20191005   for:解决每次请求,都重写redis中 token缓存问题
			return true;
		}
		return false;
	}
 
Example 22
Source Project: jeecg-boot   Source File: SysDepartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
//@RequiresRoles({"admin"})
@RequestMapping(value = "/add", method = RequestMethod.POST)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	Result<SysDepart> result = new Result<SysDepart>();
	String username = JwtUtil.getUserNameByToken(request);
	try {
		sysDepart.setCreateBy(username);
		sysDepartService.saveDepartData(sysDepart, username);
		//清除部门树内存
		// FindsDepartsChildrenUtil.clearSysDepartTreeList();
		// FindsDepartsChildrenUtil.clearDepartIdModel();
		result.success("添加成功!");
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		result.error500("操作失败");
	}
	return result;
}
 
Example 23
Source Project: jeecg-boot   Source File: SysDepartController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 编辑数据 编辑部门的部分数据,并保存到数据库
 * 
 * @param sysDepart
 * @return
 */
//@RequiresRoles({"admin"})
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
	String username = JwtUtil.getUserNameByToken(request);
	sysDepart.setUpdateBy(username);
	Result<SysDepart> result = new Result<SysDepart>();
	SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
	if (sysDepartEntity == null) {
		result.error500("未找到对应实体");
	} else {
		boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
		// TODO 返回false说明什么?
		if (ok) {
			//清除部门树内存
			//FindsDepartsChildrenUtil.clearSysDepartTreeList();
			//FindsDepartsChildrenUtil.clearDepartIdModel();
			result.success("修改成功!");
		}
	}
	return result;
}
 
Example 24
Source Project: jeecg-boot   Source File: LoginController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 退出登录
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/logout")
public Result<Object> logout(HttpServletRequest request,HttpServletResponse response) {
	//用户退出逻辑
    String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
    if(oConvertUtils.isEmpty(token)) {
    	return Result.error("退出登录失败!");
    }
    String username = JwtUtil.getUsername(token);
	LoginUser sysUser = sysBaseAPI.getUserByName(username);
    if(sysUser!=null) {
    	sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功!", CommonConstant.LOG_TYPE_1, null);
    	log.info(" 用户名:  "+sysUser.getRealname()+",退出成功! ");
    	//清空用户登录Token缓存
    	redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
    	//清空用户登录Shiro权限缓存
		redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
		//清空用户的缓存信息(包括部门信息),例如sys:cache:user::<username>
		redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
		//调用shiro的logout
		SecurityUtils.getSubject().logout();
    	return Result.ok("退出登录成功!");
    }else {
    	return Result.error("Token无效!");
    }
}
 
Example 25
Source Project: jeecg-boot   Source File: ThirdLoginController.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@RequestMapping(value = "/getLoginUser/{token}", method = RequestMethod.GET)
@ResponseBody
public Result<JSONObject> getLoginUser(@PathVariable("token") String token) throws Exception {
	Result<JSONObject> result = new Result<JSONObject>();
	String username = JwtUtil.getUsername(token);
	
	//1. 校验用户是否有效
	SysUser sysUser = sysUserService.getUserByName(username);
	result = sysUserService.checkUserIsEffective(sysUser);
	if(!result.isSuccess()) {
		return result;
	}
	JSONObject obj = new JSONObject();
	//用户登录信息
	obj.put("userInfo", sysUser);
	//token 信息
	obj.put("token", token);
	result.setResult(obj);
	result.setSuccess(true);
	result.setCode(200);
	sysBaseAPI.addLog("用户名: " + username + ",登录成功[第三方用户]!", CommonConstant.LOG_TYPE_1, null);
	return result;
}
 
Example 26
Source Project: jeecg-cloud   Source File: ShiroRealm.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 校验token的有效性
 *
 * @param token
 */
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
	// 解密获得username,用于和数据库进行对比
	String username = JwtUtil.getUsername(token);
	if (username == null) {
		throw new AuthenticationException("token非法无效!");
	}

	// 查询用户信息
	log.info("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
	//采用缓存方式获取登录用户信息,提高并发性能(gateway)
       //LoginUser loginUser = sysBaseRemoteApi.getUserByName(username).getResult();
	LoginUser loginUser = (LoginUser) redisUtil.get(CacheConstant.SYS_USERS_CACHE_JWT+":"+token);
	if (loginUser == null) {
		throw new AuthenticationException("用户不存在!");
	}
       // 判断用户状态
       if (loginUser.getStatus() != 1) {
           throw new AuthenticationException("账号已被锁定,请联系管理员!");
       }
	// 校验token是否超时失效 & 或者账号密码是否错误
	if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
		throw new AuthenticationException("Token失效,请重新登录!");
	}

	return loginUser;
}
 
Example 27
Source Project: jeecg-cloud   Source File: PermissionDataAspect.java    License: Apache License 2.0 5 votes vote down vote up
private void authDataHandler(HttpServletRequest request, String component) {
	List<SysPermission> currentSyspermission = null;
	if(oConvertUtils.isNotEmpty(component)) {
		//1.通过注解属性pageComponent 获取菜单
		currentSyspermission = sysUserRemoteApi.queryComponentPermission(component);
	}else {
		String requestMethod = request.getMethod();
		String requestPath = request.getRequestURI().substring(request.getContextPath().length());
		requestPath = filterUrl(requestPath);
		log.info("拦截请求 >> "+requestPath+";请求类型 >> "+requestMethod);
		currentSyspermission = sysUserRemoteApi.queryRequestPermission(requestMethod, requestPath);
	}
	//3.通过用户名+菜单ID 找到权限配置信息 放到request中去
	if(currentSyspermission!=null && currentSyspermission.size()>0) {
		String username = JwtUtil.getUserNameByToken(request);
		List<SysPermissionDataRuleModel> dataRules = new ArrayList<SysPermissionDataRuleModel>();
		for (SysPermission sysPermission : currentSyspermission) {
			// update-begin--Author:scott Date:20191119 for:数据权限规则编码不规范,项目存在相同包名和类名 #722
			List<SysPermissionDataRule> temp = sysUserRemoteApi.queryUserDataRule(username, sysPermission.getId());
			if(temp!=null && temp.size()>0) {
				//dataRules.addAll(temp);
				dataRules = oConvertUtils.entityListToModelList(temp,SysPermissionDataRuleModel.class);
			}
			// update-end--Author:scott Date:20191119 for:数据权限规则编码不规范,项目存在相同包名和类名 #722
		}
		if(dataRules!=null && dataRules.size()>0) {
			JeecgDataAutorUtils.installDataSearchConditon(request, dataRules);
			SysUserCacheInfo userinfo = sysUserRemoteApi.getCacheUser(username);
			JeecgDataAutorUtils.installUserInfo(request, userinfo);
		}
	}
}
 
Example 28
Source Project: jeecg-cloud   Source File: TestWebController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/login")
public ResponseBean login(@RequestParam("username") String username,
                          @RequestParam("password") String password) {
	SysUser user = userService.getUserByName(username);
	if(user==null) {
		return new ResponseBean(200, "用户不存在!", JwtUtil.sign(username, user.getPassword()));
	}
	String passwordEncode = PasswordUtil.encrypt(username, password, user.getSalt());
    if (passwordEncode.equals(user.getPassword())) {
        return new ResponseBean(200, "Login success", JwtUtil.sign(username, user.getPassword()));
    } else {
        throw new UnauthorizedException();
    }
}
 
Example 29
Source Project: jeecg-cloud   Source File: LoginController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 退出登录
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/logout")
public Result<Object> logout(HttpServletRequest request,HttpServletResponse response) {
	//用户退出逻辑
    String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
    if(oConvertUtils.isEmpty(token)) {
    	return Result.error("退出登录失败!");
    }
    String username = JwtUtil.getUsername(token);
	LoginUser sysUser = sysBaseAPI.getUserByName(username);
    if(sysUser!=null) {
    	sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功!", CommonConstant.LOG_TYPE_1, null);
    	log.info(" 用户名:  "+sysUser.getRealname()+",退出成功! ");
    	//清空用户登录Token缓存
    	redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
    	//清空用户登录Shiro权限缓存
		redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
		//清空用户的缓存信息(包括部门信息),例如sys:cache:user::<username>
		redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
		redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE_JWT, sysUser.getUsername()));
		//调用shiro的logout
		SecurityUtils.getSubject().logout();
    	return Result.ok("退出登录成功!");
    }else {
    	return Result.error("Token无效!");
    }
}
 
Example 30
Source Project: jeecg-cloud   Source File: LoginController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 用户信息
 *
 * @param sysUser
 * @param result
 * @return
 */
private Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {
	String syspassword = sysUser.getPassword();
	String username = sysUser.getUsername();
	// 生成token
	String token = JwtUtil.sign(username, syspassword);
       // 设置token缓存有效时间
	redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);

	//------------------------------------------------------------------------------------------
	LoginUser vo = new LoginUser();
	BeanUtils.copyProperties(sysUser,vo);
	vo.setPassword(SecureUtil.md5(sysUser.getPassword()));
	redisUtil.set(CacheConstant.SYS_USERS_CACHE_JWT +":" +token, vo);
	//------------------------------------------------------------------------------------------
	redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);

	// 获取用户部门信息
	JSONObject obj = new JSONObject();
	List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
	obj.put("departs", departs);
	if (departs == null || departs.size() == 0) {
		obj.put("multi_depart", 0);
	} else if (departs.size() == 1) {
		sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
		obj.put("multi_depart", 1);
	} else {
		obj.put("multi_depart", 2);
	}
	obj.put("token", token);
	obj.put("userInfo", sysUser);
	obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
	result.setResult(obj);
	result.success("登录成功");
	return result;
}