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);
|
}
|
}
|