|
|
|
@ -2,28 +2,41 @@ package com.project.ding.utils; |
|
|
|
|
|
|
|
import io.jsonwebtoken.Claims; |
|
|
|
import io.jsonwebtoken.Jwts; |
|
|
|
import io.jsonwebtoken.SignatureAlgorithm; |
|
|
|
import io.jsonwebtoken.security.Keys; |
|
|
|
import jakarta.annotation.PostConstruct; |
|
|
|
import org.springframework.beans.factory.annotation.Value; |
|
|
|
import org.springframework.stereotype.Component; |
|
|
|
|
|
|
|
import java.nio.charset.StandardCharsets; |
|
|
|
import java.security.Key; |
|
|
|
import java.util.Date; |
|
|
|
import java.util.List; |
|
|
|
|
|
|
|
@Component |
|
|
|
public class JwtUtils { |
|
|
|
private static final Key KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); |
|
|
|
@Value("${jwt.secret:my-very-fixed-and-secure-secret-key-1234567890}") |
|
|
|
private String secret; |
|
|
|
|
|
|
|
private static final long EXPIRE = 86400000; // 24小时
|
|
|
|
private Key key; |
|
|
|
|
|
|
|
@PostConstruct |
|
|
|
public void init() { |
|
|
|
// 2. 将字符串转换为固定的 Key 对象
|
|
|
|
// 使用固定的字节数组,保证每次重启生成的 Key 对象在逻辑上是一致的
|
|
|
|
byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8); |
|
|
|
this.key = Keys.hmacShaKeyFor(keyBytes); |
|
|
|
} |
|
|
|
public String createToken(String userId, List<String> roles) { |
|
|
|
return Jwts.builder() |
|
|
|
.setSubject(userId) |
|
|
|
.claim("roles", roles) |
|
|
|
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) |
|
|
|
.signWith(KEY).compact(); |
|
|
|
.signWith(key).compact(); |
|
|
|
} |
|
|
|
|
|
|
|
public Claims parseToken(String token) { |
|
|
|
return Jwts.parserBuilder().setSigningKey(KEY).build().parseClaimsJws(token).getBody(); |
|
|
|
return Jwts.parserBuilder().setSigningKey(key).build() |
|
|
|
.parseClaimsJws(token).getBody(); |
|
|
|
} |
|
|
|
} |