在使用七牛云时,开发者可能会遇到回调签名验证不一致的问题,这可能会导致应用逻辑上的错误。让我们深入探讨这一问题的原因以及如何解决。
七牛云在进行回调时,会在请求的头部包含一个 Authorization 字段,其格式为 QBox
用户提供了一段代码,用于验证七牛云的回调签名,但发现计算出的签名与七牛云提供的签名不一致。具体代码如下:
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; }
用户提到的问题是,计算出的 computed_sign 始终与七牛云传来的签名不一致,并且前端没有发送请求体,导致后端获取到的 php://input 为空。
为了解决这个问题,修改后的代码应该考虑以下几点:
下面是根据这些考虑点修改后的代码:
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)); }
这个修改后的版本增加了对 URI 查询字符串的处理,并确保在计算签名时考虑到了请求体的内容,即使请求体可能为空。同时,详细的调试信息也增加了,以便于更快地诊断和解决问题。
通过这些调整,开发者应该能够更好地处理七牛云的回调签名验证问题,确保应用的安全性和正确性。
以上就是如何解决七牛云回调签名验证不一致的问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号