29 lines
1.1 KiB
Java
29 lines
1.1 KiB
Java
package com.baiyue.integration.security;
|
|||
|
|
|
||
|
|
import org.springframework.beans.factory.annotation.Value;
|
||
|
|
import org.springframework.http.HttpStatus;
|
||
|
|
import org.springframework.stereotype.Component;
|
||
|
|
import org.springframework.web.server.ResponseStatusException;
|
||
|
|
|
||
|
|
import java.nio.charset.StandardCharsets;
|
||
|
|
import java.security.MessageDigest;
|
||
|
|
|
||
|
|
@Component
|
||
|
|
public class InternalServiceTokenGuard {
|
||
|
|
private final byte[] expectedToken;
|
||
|
|
|
||
|
|
public InternalServiceTokenGuard(@Value("${baiyue.security.internal-service-token}") String token) {
|
||
|
|
if (token == null || 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 ResponseStatusException(HttpStatus.UNAUTHORIZED, "内部服务令牌无效");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|