I have the following PHP curl code to generate a security token within an Application. When I run this code it works perfect.
$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);
But at the moment I need a Guzzle version of this Curl script and that's where this issue begins.
I found different ways to handle the Authentication within Guzzle but so far nothing works.
This is what I came up with.
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()
]);
}
Instead of returning a security token, I get an error message "401 Unauthorized` response" - which means no correct authentication received.
What exactly am I doing wrong?
Thank you in advance.