| package com.example.g8backend.util; |
| import io.jsonwebtoken.*; |
| import org.springframework.stereotype.Component; |
| import javax.crypto.SecretKey; |
| private final SecretKey secretKey; |
| private final long expirationMs; |
| public JwtUtil(SecretKey secretKey) { |
| this.secretKey = secretKey; |
| this.expirationMs = 3600_000; // 1小时 |
| public String generateToken(long userId) { |
| Date expiryDate = new Date(now.getTime() + expirationMs); |
| .signWith(secretKey, Jwts.SIG.HS256) |
| public Long validateTokenAndGetUserId(String token) { |
| Jws<Claims> claims = Jwts.parser() |
| .parseSignedClaims(token); |
| return claims.getPayload().get("id", Long.class); |
| } catch (JwtException e) { |
| throw new RuntimeException("Token无效或过期", e); |