blob: f11e678489f451763327c3d061211d49044f49a9 [file] [log] [blame]
package com.example.g8backend.util;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
@Component
public class JwtUtil {
private final SecretKey secretKey;
private final long expirationMs;
public JwtUtil(SecretKey secretKey) {
this.secretKey = secretKey;
this.expirationMs = 3600_000; // 1小时
}
// 生成 JWT Token
public String generateToken(long userId) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + expirationMs);
return Jwts.builder()
.claim("id", userId)
.issuedAt(now)
.expiration(expiryDate)
.signWith(secretKey, Jwts.SIG.HS256)
.compact();
}
// 验证Token并解析用户名
public Long validateTokenAndGetUserId(String token) {
try {
Jws<Claims> claims = Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token);
return claims.getPayload().get("id", Long.class);
} catch (JwtException e) {
throw new RuntimeException("Token无效或过期", e);
}
}
}