CloudStack API signing request - PHP

294 views Asked by At

I want to run Cloudstack commands via API calls, but obviously, i'm failing on generate signature step.

<?php

$baseurl = "http://localhost:8080/client/api?";

$response = "response=json";

$command = "command=listUsers";
$apikey = "Z-dr9dp6gZbKmrl9stAm6uGBSWqSonMhc2i-nqVlSG6MlpvqWFWW1uVJEZnrrwq_drQXDWRFTGwZ1p_qarLzwQ";
$secretkey = "p_iiuI3oDxBCxmUgceAHYf-f9uotX9B-uK2qxmVAT_bbYfPdhiePnlPRjbL6CvtPH8gDbjIh8uGPmP1KjN6HBQ";


$hash = hash_hmac("sha1",strtolower($apikey . "&" . $command),$secretkey, true);
$base64encoded = base64_encode($hash);
$signature = "signature=" . urlencode($base64encoded);

$link = $baseurl . "apikey=" . $apikey . "&" . $command . "&" . $response . "&" . $signature;


$responseconents = file_get_contents($link);


print $link;

?>

Generated Url link: http://localhost:8080/client/api?apikey=Z-dr9dp6gZbKmrl9stAm6uGBSWqSonMhc2i-nqVlSG6MlpvqWFWW1uVJEZnrrwq_drQXDWRFTGwZ1p_qarLzwQ&command=listUsers&response=json&signature=H57C0kDRw4CZjEPQvFvrrPEJ%2FiM%3D

Error i'm getting:

HTTP request failed! HTTP/1.1 401 Unauthorized

Used this guide (from slide 11) as reference, but it's for python.

EDIT

after trying @CBroe suggestions

$baseurl = "http://localhost:8080/client/api?";

$response = "response=json";

$command = "command=listUsers";
$apikey = "apikey=Z-dr9dp6gZbKmrl9stAm6uGBSWqSonMhc2i-nqVlSG6MlpvqWFWW1uVJEZnrrwq_drQXDWRFTGwZ1p_qarLzwQ";
$secretkey = "p_iiuI3oDxBCxmUgceAHYf-f9uotX9B-uK2qxmVAT_bbYfPdhiePnlPRjbL6CvtPH8gDbjIh8uGPmP1KjN6HBQ";


$hash = hash_hmac("sha1",strtolower($apikey . "&" . $command . "&" . $response),$secretkey, true);
$base64encoded = base64_encode($hash);
$signature = "signature=" . urlencode($base64encoded);

$link = $baseurl  . $apikey . "&" . $command . "&" . $response . "&" . $signature;


$responsecontents = file_get_contents($link);

$responsejson = json_decode($responsecontents);

print $responsejson

If i remove print line no output, when adding print $responsejson then getting

PHP Recoverable fatal error: Object of class stdClass could not be converted to string

It's seems i no more have 401 error, but unable to see command output now.

EDIT II

After adding

var_dump($responsecontents);

at the end, it works as expected, i can now see users in JSON format.

Thanks @CBroe

0

There are 0 answers