luoweijian 7 days ago
parent
commit
1108d65520
  1. 21
      src/main/java/com/project/ding/utils/JwtUtils.java
  2. 4
      src/main/resources/application.yml

21
src/main/java/com/project/ding/utils/JwtUtils.java

@ -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();
}
}

4
src/main/resources/application.yml

@ -74,4 +74,6 @@ ding:
corpId: ding13d71da66ad91ff0f5bf40eda33b7ba0
algo:
clusterUrl: /semantic-cluster
baseUrl: http://172.16.204.50:8002
baseUrl: http://172.16.204.50:8002
jwt:
secret: "my-very-fixed-and-secure-secret-key-1234567890"
Loading…
Cancel
Save