暂存提交
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
package com.baiyue.eventbridge.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 String expectedToken;
|
||||
|
||||
public InternalServiceTokenGuard(@Value("${baiyue.security.internal-service-token:}") String expectedToken) {
|
||||
this.expectedToken = expectedToken;
|
||||
}
|
||||
|
||||
public void verify(String actualToken) {
|
||||
if (expectedToken == null || expectedToken.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "内部事件接收令牌未配置,接口已关闭");
|
||||
}
|
||||
byte[] expected = expectedToken.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] actual = actualToken == null ? new byte[0] : actualToken.getBytes(StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(expected, actual)) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "内部服务令牌无效");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user