This commit is contained in:
@@ -11,6 +11,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
@@ -20,16 +21,42 @@ import java.util.Date;
|
||||
@Slf4j
|
||||
public class JwtService {
|
||||
|
||||
private static final String INSECURE_DEFAULT_SECRET = "please-change-this-secret-please-rotate-at-least-32-bytes";
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private final AuthProperties props;
|
||||
|
||||
private volatile SecretKey cachedKey;
|
||||
|
||||
private SecretKey signingKey() {
|
||||
byte[] keyBytes = props.getJwtSecret().getBytes(StandardCharsets.UTF_8);
|
||||
if (keyBytes.length < 32) {
|
||||
byte[] padded = new byte[32];
|
||||
System.arraycopy(keyBytes, 0, padded, 0, keyBytes.length);
|
||||
keyBytes = padded;
|
||||
SecretKey key = cachedKey;
|
||||
if (key == null) {
|
||||
synchronized (this) {
|
||||
key = cachedKey;
|
||||
if (key == null) {
|
||||
String configured = props.getJwtSecret();
|
||||
boolean insecure = configured == null || configured.isBlank()
|
||||
|| INSECURE_DEFAULT_SECRET.equals(configured.trim());
|
||||
byte[] keyBytes;
|
||||
if (insecure) {
|
||||
keyBytes = new byte[32];
|
||||
SECURE_RANDOM.nextBytes(keyBytes);
|
||||
log.warn("[auth] AIIMAGE_JWT_SECRET 未配置或仍为默认值,已自动生成随机密钥;"
|
||||
+ "服务重启后已签发的 token 将失效,请通过环境变量 AIIMAGE_JWT_SECRET 配置固定密钥");
|
||||
} else {
|
||||
keyBytes = configured.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
if (keyBytes.length < 32) {
|
||||
byte[] padded = new byte[32];
|
||||
System.arraycopy(keyBytes, 0, padded, 0, keyBytes.length);
|
||||
keyBytes = padded;
|
||||
}
|
||||
key = Keys.hmacShaKeyFor(keyBytes);
|
||||
cachedKey = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
return key;
|
||||
}
|
||||
|
||||
public String issue(Long userId, String username, String deviceId) {
|
||||
|
||||
Reference in New Issue
Block a user