mirror of
https://gitee.com/dromara/RuoYi-Cloud-Plus.git
synced 2025-09-08 05:17:42 +00:00
优化获取缓存信息方式
This commit is contained in:
@@ -7,7 +7,6 @@ import org.springframework.util.PatternMatchUtils;
|
||||
import com.ruoyi.common.core.exception.auth.NotLoginException;
|
||||
import com.ruoyi.common.core.exception.auth.NotPermissionException;
|
||||
import com.ruoyi.common.core.exception.auth.NotRoleException;
|
||||
import com.ruoyi.common.core.utils.SecurityUtils;
|
||||
import com.ruoyi.common.core.utils.SpringUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.common.security.annotation.Logical;
|
||||
@@ -15,6 +14,7 @@ import com.ruoyi.common.security.annotation.RequiresLogin;
|
||||
import com.ruoyi.common.security.annotation.RequiresPermissions;
|
||||
import com.ruoyi.common.security.annotation.RequiresRoles;
|
||||
import com.ruoyi.common.security.service.TokenService;
|
||||
import com.ruoyi.common.security.utils.SecurityUtils;
|
||||
import com.ruoyi.system.api.model.LoginUser;
|
||||
|
||||
/**
|
||||
@@ -32,6 +32,27 @@ public class AuthLogic
|
||||
|
||||
public TokenService tokenService = SpringUtils.getBean(TokenService.class);
|
||||
|
||||
/**
|
||||
* 会话注销
|
||||
*/
|
||||
public void logout()
|
||||
{
|
||||
String token = SecurityUtils.getToken();
|
||||
if (token == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
logoutByToken(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话注销,根据指定Token
|
||||
*/
|
||||
public void logoutByToken(String token)
|
||||
{
|
||||
tokenService.delLoginUser(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检验用户是否已经登录,如未登录,则抛出异常
|
||||
*/
|
||||
@@ -52,7 +73,7 @@ public class AuthLogic
|
||||
{
|
||||
throw new NotLoginException("未提供token");
|
||||
}
|
||||
LoginUser loginUser = tokenService.getLoginUser(token);
|
||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
||||
if (loginUser == null)
|
||||
{
|
||||
throw new NotLoginException("无效的token");
|
||||
@@ -60,6 +81,27 @@ public class AuthLogic
|
||||
return loginUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户缓存信息, 如果未登录,则抛出异常
|
||||
*
|
||||
* @param token 前端传递的认证信息
|
||||
* @return 用户缓存信息
|
||||
*/
|
||||
public LoginUser getLoginUser(String token)
|
||||
{
|
||||
return tokenService.getLoginUser(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证当前用户有效期, 如果相差不足360分钟,自动刷新缓存
|
||||
*
|
||||
* @param loginUser 当前用户信息
|
||||
*/
|
||||
public void verifyLoginUserExpire(LoginUser loginUser)
|
||||
{
|
||||
tokenService.verifyToken(loginUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证用户是否具备某权限
|
||||
*
|
||||
|
@@ -2,6 +2,7 @@ package com.ruoyi.common.security.auth;
|
||||
|
||||
import com.ruoyi.common.security.annotation.RequiresPermissions;
|
||||
import com.ruoyi.common.security.annotation.RequiresRoles;
|
||||
import com.ruoyi.system.api.model.LoginUser;
|
||||
|
||||
/**
|
||||
* Token 权限验证工具类
|
||||
@@ -15,6 +16,24 @@ public class AuthUtil
|
||||
*/
|
||||
public static AuthLogic authLogic = new AuthLogic();
|
||||
|
||||
/**
|
||||
* 会话注销
|
||||
*/
|
||||
public static void logout()
|
||||
{
|
||||
authLogic.logout();
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话注销,根据指定Token
|
||||
*
|
||||
* @param tokenValue 指定token
|
||||
*/
|
||||
public static void logoutByToken(String token)
|
||||
{
|
||||
authLogic.logoutByToken(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检验当前会话是否已经登录,如未登录,则抛出异常
|
||||
*/
|
||||
@@ -23,6 +42,22 @@ public class AuthUtil
|
||||
authLogic.checkLogin();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户信息
|
||||
*/
|
||||
public static LoginUser getLoginUser(String token)
|
||||
{
|
||||
return authLogic.getLoginUser(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证当前用户有效期
|
||||
*/
|
||||
public static void verifyLoginUserExpire(LoginUser loginUser)
|
||||
{
|
||||
authLogic.verifyLoginUserExpire(loginUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前账号是否含有指定角色标识, 返回true或false
|
||||
*
|
||||
|
@@ -0,0 +1,33 @@
|
||||
package com.ruoyi.common.security.config;
|
||||
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import com.ruoyi.common.security.interceptor.HeaderInterceptor;
|
||||
|
||||
/**
|
||||
* 拦截器配置
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class WebMvcConfig implements WebMvcConfigurer
|
||||
{
|
||||
/** 不需要拦截地址 */
|
||||
public static final String[] excludeUrls = { "/login", "/logout", "/refresh" };
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry)
|
||||
{
|
||||
registry.addInterceptor(getHeaderInterceptor())
|
||||
.addPathPatterns("/**")
|
||||
.excludePathPatterns(excludeUrls)
|
||||
.order(-10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义请求头拦截器
|
||||
*/
|
||||
public HeaderInterceptor getHeaderInterceptor()
|
||||
{
|
||||
return new HeaderInterceptor();
|
||||
}
|
||||
}
|
@@ -0,0 +1,53 @@
|
||||
package com.ruoyi.common.security.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.AsyncHandlerInterceptor;
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
import com.ruoyi.common.core.context.SecurityContextHolder;
|
||||
import com.ruoyi.common.core.utils.ServletUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.common.security.auth.AuthUtil;
|
||||
import com.ruoyi.common.security.utils.SecurityUtils;
|
||||
import com.ruoyi.system.api.model.LoginUser;
|
||||
|
||||
/**
|
||||
* 自定义请求头拦截器,将Header数据封装到线程变量中方便获取
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class HeaderInterceptor implements AsyncHandlerInterceptor
|
||||
{
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
|
||||
{
|
||||
if (!(handler instanceof HandlerMethod))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
|
||||
SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
|
||||
SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
|
||||
|
||||
String token = SecurityUtils.getToken();
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
LoginUser loginUser = AuthUtil.getLoginUser(token);
|
||||
if (StringUtils.isNotNull(loginUser))
|
||||
{
|
||||
AuthUtil.verifyLoginUserExpire(loginUser);
|
||||
SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception
|
||||
{
|
||||
SecurityContextHolder.remove();
|
||||
}
|
||||
}
|
@@ -7,13 +7,14 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.ruoyi.common.core.constant.CacheConstants;
|
||||
import com.ruoyi.common.core.constant.Constants;
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
import com.ruoyi.common.core.utils.IdUtils;
|
||||
import com.ruoyi.common.core.utils.SecurityUtils;
|
||||
import com.ruoyi.common.core.utils.JwtUtils;
|
||||
import com.ruoyi.common.core.utils.ServletUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.common.core.utils.ip.IpUtils;
|
||||
import com.ruoyi.common.redis.service.RedisService;
|
||||
import com.ruoyi.common.security.utils.SecurityUtils;
|
||||
import com.ruoyi.system.api.model.LoginUser;
|
||||
|
||||
/**
|
||||
@@ -27,31 +28,41 @@ public class TokenService
|
||||
@Autowired
|
||||
private RedisService redisService;
|
||||
|
||||
private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;
|
||||
protected static final long MILLIS_SECOND = 1000;
|
||||
|
||||
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
|
||||
|
||||
private final static long expireTime = CacheConstants.EXPIRATION;
|
||||
|
||||
private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
|
||||
|
||||
protected static final long MILLIS_SECOND = 1000;
|
||||
private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;
|
||||
|
||||
/**
|
||||
* 创建令牌
|
||||
*/
|
||||
public Map<String, Object> createToken(LoginUser loginUser)
|
||||
{
|
||||
// 生成token
|
||||
String token = IdUtils.fastUUID();
|
||||
Long userId = loginUser.getSysUser().getUserId();
|
||||
String userName = loginUser.getSysUser().getUserName();
|
||||
loginUser.setToken(token);
|
||||
loginUser.setUserid(loginUser.getSysUser().getUserId());
|
||||
loginUser.setUsername(loginUser.getSysUser().getUserName());
|
||||
loginUser.setUserid(userId);
|
||||
loginUser.setUsername(userName);
|
||||
loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
|
||||
refreshToken(loginUser);
|
||||
|
||||
// 保存或更新用户token
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("access_token", token);
|
||||
map.put("expires_in", EXPIRE_TIME);
|
||||
redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
|
||||
return map;
|
||||
// Jwt存储信息
|
||||
Map<String, Object> claimsMap = new HashMap<String, Object>();
|
||||
claimsMap.put(SecurityConstants.USER_KEY, token);
|
||||
claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
|
||||
claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
|
||||
|
||||
// 接口返回信息
|
||||
Map<String, Object> rspMap = new HashMap<String, Object>();
|
||||
rspMap.put("access_token", JwtUtils.createToken(claimsMap));
|
||||
rspMap.put("expires_in", expireTime);
|
||||
return rspMap;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,13 +94,20 @@ public class TokenService
|
||||
*/
|
||||
public LoginUser getLoginUser(String token)
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
LoginUser user = null;
|
||||
try
|
||||
{
|
||||
String userKey = getTokenKey(token);
|
||||
LoginUser user = redisService.getCacheObject(userKey);
|
||||
return user;
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
String userkey = JwtUtils.getUserKey(token);
|
||||
user = redisService.getCacheObject(getTokenKey(userkey));
|
||||
return user;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
catch (Exception e)
|
||||
{
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,12 +121,30 @@ public class TokenService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除用户缓存信息
|
||||
*/
|
||||
public void delLoginUser(String token)
|
||||
{
|
||||
if (StringUtils.isNotEmpty(token))
|
||||
{
|
||||
String userKey = getTokenKey(token);
|
||||
redisService.deleteObject(userKey);
|
||||
String userkey = JwtUtils.getUserKey(token);
|
||||
redisService.deleteObject(getTokenKey(userkey));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证令牌有效期,相差不足120分钟,自动刷新缓存
|
||||
*
|
||||
* @param loginUser
|
||||
*/
|
||||
public void verifyToken(LoginUser loginUser)
|
||||
{
|
||||
long expireTime = loginUser.getExpireTime();
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
|
||||
{
|
||||
refreshToken(loginUser);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,10 +156,10 @@ public class TokenService
|
||||
public void refreshToken(LoginUser loginUser)
|
||||
{
|
||||
loginUser.setLoginTime(System.currentTimeMillis());
|
||||
loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
|
||||
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
|
||||
// 根据uuid将loginUser缓存
|
||||
String userKey = getTokenKey(loginUser.getToken());
|
||||
redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
|
||||
redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
private String getTokenKey(String token)
|
||||
|
@@ -0,0 +1,117 @@
|
||||
package com.ruoyi.common.security.utils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
||||
import com.ruoyi.common.core.constant.TokenConstants;
|
||||
import com.ruoyi.common.core.context.SecurityContextHolder;
|
||||
import com.ruoyi.common.core.utils.ServletUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.system.api.model.LoginUser;
|
||||
|
||||
/**
|
||||
* 权限获取工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SecurityUtils
|
||||
{
|
||||
/**
|
||||
* 获取用户ID
|
||||
*/
|
||||
public static Long getUserId()
|
||||
{
|
||||
return SecurityContextHolder.getUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户名称
|
||||
*/
|
||||
public static String getUsername()
|
||||
{
|
||||
return SecurityContextHolder.getUserName();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户key
|
||||
*/
|
||||
public static String getUserKey()
|
||||
{
|
||||
return SecurityContextHolder.getUserKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登录用户信息
|
||||
*/
|
||||
public static LoginUser getLoginUser()
|
||||
{
|
||||
return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求token
|
||||
*/
|
||||
public static String getToken()
|
||||
{
|
||||
return getToken(ServletUtils.getRequest());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据request获取请求token
|
||||
*/
|
||||
public static String getToken(HttpServletRequest request)
|
||||
{
|
||||
// 从header获取token标识
|
||||
String token = request.getHeader(TokenConstants.AUTHENTICATION);
|
||||
return replaceTokenPrefix(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 裁剪token前缀
|
||||
*/
|
||||
public static String replaceTokenPrefix(String token)
|
||||
{
|
||||
// 如果前端设置了令牌前缀,则裁剪掉前缀
|
||||
if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
|
||||
{
|
||||
token = token.replaceFirst(TokenConstants.PREFIX, "");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为管理员
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 结果
|
||||
*/
|
||||
public static boolean isAdmin(Long userId)
|
||||
{
|
||||
return userId != null && 1L == userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成BCryptPasswordEncoder密码
|
||||
*
|
||||
* @param password 密码
|
||||
* @return 加密字符串
|
||||
*/
|
||||
public static String encryptPassword(String password)
|
||||
{
|
||||
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
return passwordEncoder.encode(password);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断密码是否相同
|
||||
*
|
||||
* @param rawPassword 真实密码
|
||||
* @param encodedPassword 加密后字符
|
||||
* @return 结果
|
||||
*/
|
||||
public static boolean matchesPassword(String rawPassword, String encodedPassword)
|
||||
{
|
||||
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
return passwordEncoder.matches(rawPassword, encodedPassword);
|
||||
}
|
||||
}
|
@@ -1,4 +1,5 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.ruoyi.common.security.config.WebMvcConfig,\
|
||||
com.ruoyi.common.security.service.TokenService,\
|
||||
com.ruoyi.common.security.aspect.PreAuthorizeAspect,\
|
||||
com.ruoyi.common.security.aspect.InnerAuthAspect,\
|
||||
|
Reference in New Issue
Block a user