wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 1 | package com.example.g8backend.util; |
| 2 | |
| 3 | import io.jsonwebtoken.*; |
| 4 | import org.springframework.stereotype.Component; |
| 5 | import javax.crypto.SecretKey; |
| 6 | import java.util.Date; |
| 7 | |
| 8 | @Component |
| 9 | public class JwtUtil { |
| 10 | |
| 11 | private final SecretKey secretKey; |
| 12 | private final long expirationMs; |
| 13 | |
| 14 | public JwtUtil(SecretKey secretKey) { |
| 15 | this.secretKey = secretKey; |
| 16 | this.expirationMs = 3600_000; // 1小时 |
| 17 | } |
| 18 | |
| 19 | // 生成 JWT Token |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 20 | public String generateToken(long userId) { |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 21 | Date now = new Date(); |
| 22 | Date expiryDate = new Date(now.getTime() + expirationMs); |
| 23 | |
| 24 | return Jwts.builder() |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 25 | .claim("id", userId) |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 26 | .issuedAt(now) |
| 27 | .expiration(expiryDate) |
| 28 | .signWith(secretKey, Jwts.SIG.HS256) |
| 29 | .compact(); |
| 30 | } |
| 31 | |
| 32 | // 验证Token并解析用户名 |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 33 | public Long validateTokenAndGetUserId(String token) { |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 34 | try { |
| 35 | Jws<Claims> claims = Jwts.parser() |
| 36 | .verifyWith(secretKey) |
| 37 | .build() |
| 38 | .parseSignedClaims(token); |
| 39 | |
wuchimedes | 223bfab | 2025-04-04 17:16:05 +0800 | [diff] [blame] | 40 | return claims.getPayload().get("id", Long.class); |
wuchimedes | 079c163 | 2025-04-02 22:01:20 +0800 | [diff] [blame] | 41 | } catch (JwtException e) { |
| 42 | throw new RuntimeException("Token无效或过期", e); |
| 43 | } |
| 44 | } |
| 45 | } |