七牛云回调签名验证不一致的原因及解决方法?

新手上路,请多包涵

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;
}

产试过bod有,因为前端没有加所以后端获取为空,生成computed_sign,一直与七牛传来的不一致

阅读 523
1 个回答
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));
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题