在PHP curl请求中使用Auth Digest头变量



我正在使用一个API,它为我提供了一个用于连接的令牌。它给出了这些指示。

然后,在所有后续调用中,都会将此令牌发送到标头变量Auth Digest中的服务器。

我不知道这意味着什么。我已经尝试了几种方法,并阅读了几个堆栈溢出问题。这是我试过的。有关详细信息,请参阅包含的代码注释。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
// I have tried setting both of these
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// In combination of the above separately, I have tried each of these individually
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Auth Digest: ' . $token));
curl_setopt($ch, CURLOPT_POST, true);
$post_data = array('Auth Digest' => $token);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_USERPWD, $token); 
// Then I execute and close, either giving me a failed response and a response that says token is not valid
$response = curl_exec($ch);
$header_sent = curl_getinfo($ch, CURLINFO_HEADER_OUT);
if (!$response) {
    echo $action . ' curl request failed';
    return false;
}
curl_close($ch);
$response_json = json_decode($response);
var_dump($response_json);

以下是一些相关的stackerflow问题,我曾试图将其应用于我的问题,但没有成功。

在PHP中使用摘要身份验证的Curl请求下载Bitbucket私有存储库

使用PHP POST到Web服务的摘要式身份验证的客户端部分

如何使用PHP curl的HTTP基本身份验证进行请求?

我需要知道他们可能期望的原始http头是什么,或者我如何使用php-ccurl来生成他们可能期待的头。

摘要授权标头通常看起来像:

Authorization: Digest _data_here_

所以在你的情况下,试试:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//... existing options here
$headers = array(
    'Authorization: Digest ' . $token,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

如果使用CURLOPT_HTTPHEADER,则只指定要发送的附加标头,而不需要在其中添加所有标头。

如果您发送的其他标头都有明确的选项,请使用这些选项,并将一个授权标头传递给CURLOPT_HTTPHEADER

最新更新