问题描述
当前的有一个对接facebook webhook的需求,所以这个接口不能加鉴权、认证。但是facebook发送的请求头中会有一个hamn-sha256的验签,本地根据接收到是负载和应用密钥计算签名,计算一致再进行一系列操作。但是根据官方文档的说明的js代码片段,计算的验签无论如何也无法匹配官方验签名。
Facebook官方说明
验证有效负载
我们使用SHA256签名对所有事件通知负载进行签名,并将签名包含在请求的“X-Hub-Signature-256”标头中,前面带有“sha256=”。您不必验证有效负载,但您应该这样做,而且我们强烈建议您这样做。
使用有效负载和应用程序的App Secret生成SHA256签名。
将您的签名与X-Hub-Signature-256标头中的签名( sha256=之后的所有内容)进行比较。如果签名匹配,则有效负载是真实的。
官方提供的js代码片段
function verifyRequestSignature(req, res, buf) {
var signature = req.headers["x-hub-signature-256"];
if (!signature) {
console.warn(`Couldn't find "x-hub-signature-256" in headers.`);
} else {
var elements = signature.split("=");
var signatureHash = elements[1];
var expectedHash = crypto
.createHmac("sha256", config.appSecret)
.update(buf)
.digest("hex");
if (signatureHash != expectedHash) {
throw new Error("Couldn't validate the request signature.");
}
}
}
根据js代码写的Java代码
byte[] hmacValue = DigestUtil.hmac(HmacAlgorithm.HmacSHA256,
FACEBOOK_APPLICATION_SECRET.getBytes(StandardCharsets.UTF_8))
.digest(body.getBytes(StandardCharsets.UTF_8));
String sig = HexUtil.encodeHexStr(hmacValue);