王飞
2025-01-23 8b878300a3b44426d20b72ad4aea0291571a76ce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.hxzkmonitor.util;
 
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bouncycastle.util.encoders.Base64;
 
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
 
/**
 *
 * jwt工具类
 *
 **/
public class JwtUtil {
 
    /**
     * 签发JWT
     * @param subject    可以是JSON数据 尽可能少
     * @param ttlMillis  token有效时间
     * @return  String
     *
     */
    public static String createJWT(String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
//                .setId(IdUtils.simpleUUID()) //唯一性
                .setSubject(subject)   // 主题
                .setIssuer("admin")    // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }
 
    /**
     * 密钥
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode("xxxxxxxx"); //自定义密钥, 不能外泄
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
 
    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
 
    /**
     * 获取用户
     * @param token
     * @return
     * @throws Exception
     */
//    public synchronized static WxUser getUser(String token) {
//        WxUser user = null;
//        String subject = null;
//        try {
//            subject = parseJWT(token).getSubject();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        WxUser userModel = JsonListUtil.jsonToBean(subject, WxUser.class);
//        if (ObjectUtil.isNotEmpty(userModel)) {
//            user = SpringUtil.getBean(WxUserMapper.class).selectWxUserById(userModel.getId());
//        }
//        return user;
//    }
}