【发布时间】:2021-09-27 06:40:35
【问题描述】:
我有以下 PHP curl 代码在应用程序中生成安全令牌。 当我运行此代码时,它运行良好。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://host.com/api/v1/auth/keys');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
curl_setopt($ch, CURLOPT_USERPWD, 'admin' . ':' . 'password');
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
但目前我需要这个 Curl 脚本的 Guzzle 版本,这就是问题的开始。
我发现了在 Guzzle 中处理身份验证的不同方法,但到目前为止没有任何效果。
这是我想出来的。
use GuzzleHttp\Client;
include "../vendor/autoload.php";
try{
$client = new Client(['base_uri' => 'https://host.com/api/v1/']);
$client->request('POST', 'auth/keys',[
'config' => [
'curl' => [
// CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => 'admin:password'
]
],
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
print_r($client->getBody()->getContents());
}catch (Exception $e) {
print_r([
"status" => false,
"message" => $e->getMessage()
]);
}
我收到一条错误消息“401 Unauthorized` response”,而不是返回安全令牌,这意味着没有收到正确的身份验证。
我到底做错了什么?
提前谢谢你。
【问题讨论】:
-
我在 curl 版本的代码中看不到路径
auth/keys。你的路径不应该只是/吗? -
通常你应该使用
'auth' => [ 'username', 'password' ]进行基本认证 -
我已经尝试了链接中的解决方案和基本身份验证。不幸的是,两者都不起作用。不知何故,CURLOPT_USERPWD 不适合 Guzzle。
-
stackoverflow.com/search?q=CURLOPT_USERPWD,您是否检查了这些问题并评估了他们的任何答案是否解决了您的问题?也就是说,我在发布到该 URL 时得到 404。您是否想使用
example.com,它在示例中为占位符 URL 明确指定?