提问人:crmpicco 提问时间:11/6/2023 更新时间:11/7/2023 访问量:54
Symfony 5.4 中密钥和有效负载的 HMAC 身份验证
HMAC authentication of secret and payload in Symfony 5.4
问:
我的 JavaScript 代码正在对我的端点进行以下 API 调用:POST
const payload = {
course: args,
recipient: roomId
};
const signature = this.calculateSignature(JSON.stringify(payload), secret);
const response = await fetch(`https://crmpicco.co.uk/app/api/dsf7s9d8797987897987`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-EchoBot-Signature-256': signature
},
body: JSON.stringify(payload)
});
calculateSignature(payload, secret) {
return "sha256=" + crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
}
在我的Symfony 5.4 PHP应用程序中,我有以下代码:
$echoSecret = "0IQgWRFC1872i6AQc3mDo3Dc48UfWATPCoRX";
$encodedPayload = json_encode(json_decode($request->getContent()));
$calculatedSecret = hash_hmac('sha256', $encodedPayload, $echoSecret);
if ($headers['x-echobot-signature-256'][0] == "sha256=" . $calculatedSecret) {
$this->getLogger()->info('The signature is valid, proceed...', [
'calculatedSecret' => $calculatedSecret,
'headerSecret' => $headers['x-echobot-signature-256'][0]
]);
} else {
$this->getLogger()->info('The signature is invalid :(', [
'calculatedSecret' => $calculatedSecret,
'headerSecret' => $headers['x-echobot-signature-256'][0]
]);
}
每次调用终结点时,身份验证都会失败并落入块中。The signature is invalid :(
else
请求如下所示:
“request”:{“stdClass”:{“course”:[“topaid33”],“recipient”:“!LjZCWlshucBDhBobTT:crm.com“}},”payload“:”{“course”:[“topaid33”],“recipient”:“!LjZCWlshucBDhBobTT:crm.com“}”,“headers”:{“接受编码”:[“gzip, 紧缩 br“],”content-type“:[”application/json“],”user-agent“:[”亚马逊 CloudFront“],”x-amz-cf-id“:[”ndCQJ9lvWATP_vSerFFFFaqHBhYqOn_wdSLF2vWBShXCBA==“],”x-cloudfront-key“:[”RFC1872“],”x-matrixbot-signature-256“:[”sha256=3577f59ea6f1dd44af8af2e924009338787897987987a029ccf818ae92ee2cdb99“],”x-forwarded-port“:[”443“],”x-forwarded-proto“:[”https“],”content-length“:[”78“],”via“:[”1.1 IP-10-82-2-81防护等级 (Varnish/7.2)“],”host“:[”s.crmpicco.co.uk“],”x-varnish“:[”3735722“],”x-php-ob-level“:[”1“]
我在哪里走错了一步?
答:
使用函数比较哈希值hash_equals
$signature = $request->header('x-echobot-signature-256');
$computedSignature = hash_hmac('sha256', (string) $request->getContent(), $echoSecret);
hash_equals($signature, $computedSignature)
评论