package com.baiyue.integration.security; import jakarta.annotation.PostConstruct; import com.baiyue.common.core.api.ResultCode; import com.baiyue.common.core.exception.BizException; 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 { private static final String INSECURE_PLACEHOLDER = "change-me-to-an-internal-token-at-least-32-bytes-long"; @Value("${baiyue.security.internal-service-token}") private String token; private byte[] expectedToken; @PostConstruct void initializeToken() { if (token == null || token.isBlank() || INSECURE_PLACEHOLDER.equals(token) || token.getBytes(StandardCharsets.UTF_8).length < 32) { throw new IllegalStateException("INTERNAL_SERVICE_TOKEN 必须配置为至少 32 字节的安全令牌"); } 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)) { throw new BizException(ResultCode.UNAUTHORIZED, "内部服务令牌无效"); } } }