RuoYi
2025-03-01 d91d0f51bb5eff7bed395dcfb388996fefbbd3c3
src/main/java/com/ruoyi/framework/security/service/TokenService.java
@@ -4,9 +4,12 @@
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
@@ -28,6 +31,8 @@
@Component
public class TokenService
{
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;
@@ -44,7 +49,7 @@
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    private static final Long MILLIS_MINUTE_TWENTY = 20 * 60 * 1000L;
    @Autowired
    private RedisCache redisCache;
@@ -71,6 +76,7 @@
            }
            catch (Exception e)
            {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
@@ -114,20 +120,21 @@
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        claims.put(Constants.JWT_USERNAME, loginUser.getUsername());
        return createToken(claims);
    }
    /**
     * 验证令牌有效期,相差不足20分钟,自动刷新缓存
     * 
     * @param token 令牌
     * @param loginUser 登录信息
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        if (expireTime - currentTime <= MILLIS_MINUTE_TWENTY)
        {
            refreshToken(loginUser);
        }
@@ -146,7 +153,7 @@
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }
    /**
     * 设置用户代理信息
     * 
@@ -155,13 +162,13 @@
    public void setUserAgent(LoginUser loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }
    /**
     * 从数据声明生成令牌
     *
@@ -220,6 +227,6 @@
    private String getTokenKey(String uuid)
    {
        return Constants.LOGIN_TOKEN_KEY + uuid;
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
}