首页 > 解决方案 > CloudStack API 签名请求 - PHP

问题描述

我想通过 API 调用运行 Cloudstack 命令,但显然,我在生成签名步骤时失败了。

<?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;

?>

生成的网址链接:http://localhost:8080/client/api?apikey=Z-dr9dp6gZbKmrl9stAm6uGBSWqSonMhc2i-nqVlSG6MlpvqWFWW1uVJEZnrrwq_drQXDWRFTGwZ1p_qarLzwQ&command=listUsers&response=json&signature=H57C0kDRw4CZjEPQvFvrrPEJ%2FiM%3D

我得到的错误:

HTTP 请求失败!HTTP/1.1 401 未经授权

使用指南(来自幻灯片 11)作为参考,但它适用于 python。

编辑

在尝试了@CBroe 的建议之后

$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

如果我删除打印行没有输出,添加时print $responsejson然后得到

PHP 可恢复的致命错误:stdClass 类的对象无法转换为字符串

似乎我不再有 401 错误,但现在无法看到命令输出。

编辑二

添加后

var_dump($responsecontents);

最后,它按预期工作,我现在可以看到 JSON 格式的用户。

谢谢@CBroe

标签: phpapache-cloudstack

解决方案


推荐阅读