我有以下 PHP 卷曲代码来在应用程序中生成安全令牌。 当我运行这段代码时,它工作得非常完美。
$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`响应” - 这意味着没有收到正确的身份验证。
我到底做错了什么?
提前谢谢您。
我相信你不太清楚如何在guzzle中使用curl选项 仅使用curl作为请求选项,无需使用配置。(参见docs)
<?php
require "../vendor/autoload.php";
use GuzzleHttp\Client;
try{
$client = new Client(['base_uri' => 'https://host.com/api/v1/']);
$guzzleResponse = $client->request('POST', 'auth/keys', [
'curl' => [
CURLOPT_USERPWD => 'admin:password'
],
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
print_r($guzzleResponse->getBody()->getContents());
} catch (GuzzleHttp\Exception\RequestException $e) {
print_r([
"status" => false,
"message" => $e->getMessage(),
]);// you can use logs here like monolog library
} catch(Exception $e){
print_r([
"status" => false,
"message" => $e->getMessage(),
]);
}
参考this答案,我相信您也可以使用Basic Auth http header。
$encodedAuth = base64_encode( $usename.":".$passwd);
// ... other same as above
$guzzleResponse = $client->request('POST', 'auth/keys', [
'headers' => [
'Authorization' => 'Bearer '. $encodedAuth,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
// ... other same as above
我必须做“授权”=>“基本”