
在使用七牛云进行文件管理时,回调签名验证是确保数据安全的关键步骤。然而,有时会出现回调签名验证不一致的情况,导致验证失败。以下是问题的分析和解决方案。
在给定的问题内容中,代码尝试验证七牛云的回调签名,但验证结果始终与七牛云传来的签名不匹配。具体代码如下:
<code>public function verifyCallbackSignature(Request $request): bool
{
$authstr = $request->header('Authorization');
if (empty($authstr) || strpos($authstr, "QBox ") !== 0) {
\support\Log::debug("签名验证失败-头部格式错误", [
'sign_content' => 'qianmingshibai'
]);
return false;
}
$auth = explode(":", substr($authstr, 5));
if (count($auth) !== 2 || $auth[0] !== env('QINIU_AK')) {
\support\Log::debug("签名验证失败-AK不匹配", [
'sign_content' => 'zhanghuAkshibai',
'auth_count' => count($auth),
'auth_ak' => $auth[0],
]);
return false;
}
$data = $request->uri() . "\n" . file_get_contents('php://input');
$re = $this->URLSafeBase64Encode(hash_hmac('sha1', $data, env('QINIU_SK'), true)) === $auth[1];
\support\Log::debug("签名验证详情", [
'data' => $data,
'computed_sign' => $this->URLSafeBase64Encode(hash_hmac('sha1', $data, env('QINIU_SK'), true)),
'received_sign' => $auth[1],
]);
return $re;
}</code>在实际测试中,发现即使尝试使用body,但由于前端没有添加body,导致后端获取的body为空,因此生成的computed_sign始终与七牛云传来的签名不一致。
为了解决这个问题,我们需要对代码进行一些调整和完善。修改后的代码如下:
<code>public function verifyCallbackSignature(Request $request): bool
{
$authstr = $request->header('Authorization');
if (empty($authstr) || strpos($authstr, "QBox ") !== 0) {
\support\Log::debug("签名验证失败-头部格式错误", [
'sign_content' => 'qianmingshibai',
'authstr' => $authstr,
]);
return false;
}
$auth = explode(":", substr($authstr, 5));
if (count($auth) !== 2 || $auth[0] !== env('QINIU_AK')) {
\support\Log::debug("签名验证失败-AK不匹配", [
'sign_content' => 'zhanghuAkshibai',
'auth_count' => count($auth),
'auth_ak' => $auth[0],
'expected_ak' => env('QINIU_AK'),
]);
return false;
}
// 获取 URI 和请求体
$uri = $request->uri();
if (!empty($_SERVER['QUERY_STRING'])) {
$uri .= '?' . $_SERVER['QUERY_STRING'];
}
$body = file_get_contents('php://input');
$data = $uri . "\n" . $body;
// 计算签名
$computed_sign = $this->URLSafeBase64Encode(hash_hmac('sha1', $data, env('QINIU_SK'), true));
// 记录调试信息
\support\Log::debug("签名验证详情", [
'uri' => $uri,
'body' => $body,
'data' => $data,
'computed_sign' => $computed_sign,
'received_sign' => $auth[1],
'secret_key' => substr(env('QINIU_SK'), 0, 4) . '****',
]);
return $computed_sign === $auth[1];
}
public function URLSafeBase64Encode($data): string
{
return str_replace([' ', '/'], ['-', '_'], base64_encode($data));
}</code>通过以上修改,可以有效解决七牛云回调签名验证不一致的问题,确保验证过程顺利进行。
以上就是七牛云回调签名验证不一致的原因是什么?如何解决这个问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号