kongdeqiang
2026-10-12 7c687dd3c8fba9f7632f5e29d94a708e5f497abd
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.custom.webui.util;
 
import com.custom.webui.config.props.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
 
/**
 * JWT 生成与解析工具。
 *
 * <p>密钥来自 {@code webui.jwt.secret},生产环境请通过环境变量注入。
 * 使用 HS256(HMAC-SHA256),密钥长度必须 >= 32 字节,否则 jjwt 会直接抛异常 ——
 * 这是刻意的fail-fast设计,避免弱密钥上线。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtUtil {
 
    private final JwtProperties jwtProperties;
 
    /** 懒加载并缓存签名密钥 */
    private volatile SecretKey cachedKey;
 
    private SecretKey key() {
        if (cachedKey == null) {
            synchronized (this) {
                if (cachedKey == null) {
                    byte[] bytes = jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8);
                    if (bytes.length < 32) {
                        throw new IllegalStateException(
                                "webui.jwt.secret 长度不足 32 字节,HS256 需要至少 256 位密钥,"
                                        + "请修改配置或注入 WEBUI_JWT_SECRET 环境变量");
                    }
                    cachedKey = Keys.hmacShaKeyFor(bytes);
                }
            }
        }
        return cachedKey;
    }
 
    /**
     * 生成 token。
     *
     * @param userId   用户 id,写入 subject
     * @param username 用户名,写入自定义 claim
     * @param role     角色,写入自定义 claim,便于免查库做粗粒度鉴权
     */
    public String generateToken(Long userId, String username, String role) {
        Date now = new Date();
        Date expiry = new Date(now.getTime() + jwtProperties.getExpireMillis());
        return Jwts.builder()
                .setSubject(String.valueOf(userId))
                .claim("username", username)
                .claim("role", role)
                .setIssuer(jwtProperties.getIssuer())
                .setIssuedAt(now)
                .setExpiration(expiry)
                .signWith(key(), SignatureAlgorithm.HS256)
                .compact();
    }
 
    /** token 过期时间戳(毫秒),登录接口返回给前端 */
    public Long expiresAt() {
        return System.currentTimeMillis() + jwtProperties.getExpireMillis();
    }
 
    /**
     * 解析并校验 token。
     *
     * @return 合法则返回 Claims;签名错误、过期、格式非法统一返回 null
     */
    public Claims parse(String token) {
        if (token == null || token.isBlank()) {
            return null;
        }
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key())
                    .requireIssuer(jwtProperties.getIssuer())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException | IllegalArgumentException e) {
            // 不打印完整 token,避免日志泄露凭证
            log.debug("JWT 校验失败: {}", e.getMessage());
            return null;
        }
    }
 
    /** 从 token 中取用户 id,失败返回 null */
    public Long getUserId(String token) {
        Claims claims = parse(token);
        if (claims == null) {
            return null;
        }
        try {
            return Long.valueOf(claims.getSubject());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    /** 从 token 中取用户名 */
    public String getUsername(String token) {
        Claims claims = parse(token);
        return claims == null ? null : claims.get("username", String.class);
    }
 
    /** 从 token 中取角色 */
    public String getRole(String token) {
        Claims claims = parse(token);
        return claims == null ? null : claims.get("role", String.class);
    }
}