You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.4 KiB
44 lines
1.4 KiB
package com.example.attendance.util;
|
|
|
|
import com.example.attendance.entity.Teacher;
|
|
import io.jsonwebtoken.Claims;
|
|
import io.jsonwebtoken.Jwts;
|
|
import io.jsonwebtoken.SignatureAlgorithm;
|
|
import io.jsonwebtoken.security.Keys;
|
|
|
|
import javax.crypto.SecretKey;
|
|
import java.util.Date;
|
|
|
|
public class JWTUtil {
|
|
|
|
private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
|
|
|
|
public static String generateToken(Teacher teacher) {
|
|
return Jwts.builder()
|
|
.setSubject(teacher.getUsername())
|
|
.setIssuedAt(new Date())
|
|
.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000)) // Token 有效期 1 小时
|
|
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
|
|
.compact();
|
|
}
|
|
|
|
public static Claims extractClaims(String token) {
|
|
try {
|
|
return Jwts.parser()
|
|
.setSigningKey(SECRET_KEY)
|
|
.parseClaimsJws(token)
|
|
.getBody();
|
|
} catch (Exception e) {
|
|
throw new RuntimeException("Invalid JWT token", e); // 捕获并抛出异常
|
|
}
|
|
}
|
|
|
|
public static String getUsernameFromToken(String token) {
|
|
return extractClaims(token).getSubject();
|
|
}
|
|
|
|
public static boolean isTokenExpired(String token) {
|
|
return extractClaims(token).getExpiration().before(new Date());
|
|
}
|
|
}
|