JWT生成Token及工具类
图
JWT是JSON Web Token,用于安全传输数据的开放标准,可验证消息可靠性、完整性。不需要服务器存储会话状态,常用于身份验证和授权

依赖

<!-- JWT -->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>4.3.0</version>
</dependency>

工具类

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * JWT工具类
 */
public class JwtUtil {

    // 过期时间 30天
    private static final long EXPIRE_TIME = 1000L ;

    // 密钥
    private static final String SECRET = "VPbWUcg555zTYL7p";

    /**
     * 生成JWT令牌
     *
     * @param userId     用户ID
     * @param jsonObject 其他信息
     * @return JWT令牌
     */
    public static String generateToken(String userId, JSONObject jsonObject) {
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.create()
                .withIssuer("yourIssuer")
                .withIssuedAt(now)
                .withExpiresAt(expireTime)
                .withClaim("userId", userId)
                .withClaim("type", jsonObject)
                .sign(algorithm);
    }

    /**
     * 解析JWT令牌
     *
     * @param token JWT令牌
     * @return 解析后的JWT
     * @throws SignatureVerificationException 签名验证失败
     * @throws TokenExpiredException          令牌已过期
     * @throws JWTDecodeException             JWT解码失败
     */
    public static DecodedJWT verifyToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.require(algorithm)
                .withIssuer("yourIssuer")
                .build()
                .verify(token);
    }

    /**
     * 判断令牌是否已过期
     *
     * @param token JWT令牌
     * @return 是否已过期
     */
    public static boolean isTokenExpired(String token) {
        try {
            DecodedJWT jwt = verifyToken(token);
            Date expireTime = jwt.getExpiresAt();
            return expireTime.before(new Date());
        } catch (TokenExpiredException e) {
            return true;
        }
    }

    /**
     * 获取JWT中的用户ID
     *
     * @param token JWT令牌
     * @return 用户ID
     */
    public static String getUserId(String token) {
        DecodedJWT jwt = verifyToken(token);
        Claim userIdClaim = jwt.getClaim("userId");
        return userIdClaim.asString();
    }

    /**
     * 获取JWT中的类型字段
     *
     * @param token JWT令牌
     * @return 类型字段
     */
    public static String getType(String token) {
        DecodedJWT jwt = verifyToken(token);
        Claim typeClaim = jwt.getClaim("type");
        return typeClaim.asString();
    }

}

续签问题

需要前端配合,在Token快要失效前去后端接口拉新的Token,这个时候不需要登录,前端将新的Token进行使用即可