2026-07-30 18:01:36 +08:00
|
|
|
package com.baiyue.integration.security;
|
|
|
|
|
|
2026-08-05 10:35:07 +08:00
|
|
|
import jakarta.annotation.PostConstruct;
|
|
|
|
|
|
2026-07-31 11:58:46 +08:00
|
|
|
import com.baiyue.common.core.api.ResultCode;
|
|
|
|
|
import com.baiyue.common.core.exception.BizException;
|
2026-07-30 18:01:36 +08:00
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
import java.security.MessageDigest;
|
|
|
|
|
|
|
|
|
|
@Component
|
|
|
|
|
public class InternalServiceTokenGuard {
|
2026-08-05 16:26:10 +08:00
|
|
|
private static final String INSECURE_PLACEHOLDER =
|
|
|
|
|
"change-me-to-an-internal-token-at-least-32-bytes-long";
|
|
|
|
|
|
2026-08-05 10:35:07 +08:00
|
|
|
@Value("${baiyue.security.internal-service-token}") private String token;
|
|
|
|
|
private byte[] expectedToken;
|
2026-07-30 18:01:36 +08:00
|
|
|
|
2026-08-05 10:35:07 +08:00
|
|
|
@PostConstruct
|
|
|
|
|
void initializeToken() {
|
2026-08-05 16:26:10 +08:00
|
|
|
if (token == null
|
|
|
|
|
|| token.isBlank()
|
|
|
|
|
|| INSECURE_PLACEHOLDER.equals(token)
|
|
|
|
|
|| token.getBytes(StandardCharsets.UTF_8).length < 32) {
|
|
|
|
|
throw new IllegalStateException("INTERNAL_SERVICE_TOKEN 必须配置为至少 32 字节的安全令牌");
|
2026-07-30 18:01:36 +08:00
|
|
|
}
|
|
|
|
|
this.expectedToken = token.getBytes(StandardCharsets.UTF_8);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void verify(String actualToken) {
|
|
|
|
|
byte[] actual = actualToken == null ? new byte[0] : actualToken.getBytes(StandardCharsets.UTF_8);
|
|
|
|
|
if (!MessageDigest.isEqual(expectedToken, actual)) {
|
2026-07-31 11:58:46 +08:00
|
|
|
throw new BizException(ResultCode.UNAUTHORIZED, "内部服务令牌无效");
|
2026-07-30 18:01:36 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|