94 lines
2.3 KiB
Java
94 lines
2.3 KiB
Java
package com.tailbet.util;
|
|
|
|
import io.jsonwebtoken.Claims;
|
|
import io.jsonwebtoken.Jwts;
|
|
import io.jsonwebtoken.security.Keys;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import javax.crypto.SecretKey;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.util.Date;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* JWT工具类
|
|
*/
|
|
@Component
|
|
public class JwtUtil {
|
|
|
|
@Value("${jwt.secret}")
|
|
private String secret;
|
|
|
|
@Value("${jwt.expiration}")
|
|
private Long expiration;
|
|
|
|
private SecretKey getSigningKey() {
|
|
byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
|
|
return Keys.hmacShaKeyFor(keyBytes);
|
|
}
|
|
|
|
/**
|
|
* 生成Token
|
|
*/
|
|
public String generateToken(Long userId, String username) {
|
|
Map<String, Object> claims = new HashMap<>();
|
|
claims.put("userId", userId);
|
|
claims.put("username", username);
|
|
return createToken(claims, username);
|
|
}
|
|
|
|
private String createToken(Map<String, Object> claims, String subject) {
|
|
Date now = new Date();
|
|
Date expirationDate = new Date(now.getTime() + expiration);
|
|
|
|
return Jwts.builder()
|
|
.claims(claims)
|
|
.subject(subject)
|
|
.issuedAt(now)
|
|
.expiration(expirationDate)
|
|
.signWith(getSigningKey())
|
|
.compact();
|
|
}
|
|
|
|
/**
|
|
* 解析Token
|
|
*/
|
|
public Claims parseToken(String token) {
|
|
return Jwts.parser()
|
|
.verifyWith(getSigningKey())
|
|
.build()
|
|
.parseSignedClaims(token)
|
|
.getPayload();
|
|
}
|
|
|
|
/**
|
|
* 获取用户ID
|
|
*/
|
|
public Long getUserId(String token) {
|
|
Claims claims = parseToken(token);
|
|
return claims.get("userId", Long.class);
|
|
}
|
|
|
|
/**
|
|
* 获取用户名
|
|
*/
|
|
public String getUsername(String token) {
|
|
Claims claims = parseToken(token);
|
|
return claims.getSubject();
|
|
}
|
|
|
|
/**
|
|
* 验证Token是否过期
|
|
*/
|
|
public boolean isTokenExpired(String token) {
|
|
try {
|
|
Claims claims = parseToken(token);
|
|
return claims.getExpiration().before(new Date());
|
|
} catch (Exception e) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|