探討七牛云回調簽名驗證不一致的原因及解決方案
在使用七牛云服務時,回調簽名驗證是一個關鍵的安全措施,用于確保請求的真實性和完整性。然而,有時我們可能會遇到回調簽名驗證不一致的問題。本文將深入探討一個開發者在處理此類問題的過程中所遇到的具體問題,并提供一個經過改進的解決方案。
開發者在處理七牛云的回調簽名驗證時,使用了如下函數:
public function verifyCallbackSignature(Request $request): bool { $authstr = $request->header('Authorization'); if (empty($authstr) || strpos($authstr, "QBox ") !== 0) { supportLog::debug("簽名驗證失敗-頭部格式錯誤", [ 'sign_content' => 'qianmingshibai' ]); return false; } $auth = explode(":", substr($authstr, 5)); if (count($auth) !== 2 || $auth[0] !== env('QINIU_AK')) { supportLog::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]; supportLog::debug("簽名驗證詳情", [ 'data' => $data, 'computed_sign' => $this->URLSafeBase64Encode(hash_hmac('sha1', $data, env('QINIU_SK'), true)), 'received_sign' => $auth[1], ]); return $re; }
開發者發現即使嘗試使用body參數,回調簽名始終與七牛云傳來的簽名不一致。經過分析,發現問題主要出在以下幾個方面:
- 請求體的獲取:在原始代碼中,$data的構建方法可能不夠完整,尤其是對于帶有查詢字符串的URL。
- 簽名計算:原始代碼中的簽名計算方法和七牛云的要求可能有所出入。
為了解決這個問題,開發者對原始函數進行了如下改進:
public function verifyCallbackSignature(Request $request): bool { $authstr = $request->header('Authorization'); if (empty($authstr) || strpos($authstr, "QBox ") !== 0) { supportLog::debug("簽名驗證失敗-頭部格式錯誤", [ 'sign_content' => 'qianmingshibai', 'authstr' => $authstr, ]); return false; } $auth = explode(":", substr($authstr, 5)); if (count($auth) !== 2 || $auth[0] !== env('QINIU_AK')) { supportLog::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)); // 記錄調試信息 supportLog::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的處理更加全面,確保了在存在查詢字符串的情況下也能正確構建$data。同時,簽名計算方法也做了調整,以確保與七牛云的要求完全一致。此外,詳細的調試信息記錄也幫助開發者更容易找出問題所在。
通過上述改進,開發者成功解決了回調簽名驗證不一致的問題,確保了與七牛云服務的正常交互。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END