在azure上guzzle以获取所有虚拟主机

时间:2018-03-27 18:58:58

标签: php azure guzzle

我在Postman上有工作代码,我可以获得所有虚拟主机, 但是当我用Guzzle做PHP时,它给我带来了麻烦。 代码的第一部分我得到它,我获得了承载令牌,但随后得到虚拟主机列表,它给了我错误。

这是我的代码

$client = new \GuzzleHttp\Client();
    $res = $client->request(
        'POST',
        "https://login.microsoftonline.com/".$tenant_id."/oauth2/token",
        Array(
            'form_params' => Array(
                'grant_type'    => 'client_credentials',
                'client_id'     => $client_id,
                'client_secret' => $client_secret,
                'resource'      => 'https://management.core.windows.net/',
            )
        )
    );

    $body = $res->getBody();

    $stringBody = $body;
    $body_json = json_decode($stringBody);

    $r = $client->request(
        'GET',
        'https://management.azure.com/subscriptions/'.$subscriptionId.'/providers/Microsoft.Compute/virtualMachines?api-version=2017-12-01', [
        ['headers' => [
                'Authorization' => 'Bearer '.$body_json->access_token
            ]
        ],
        'debug' => true
    ]);

和错误:

WWW-Authenticate: Bearer authorization_uri="https://login.windows.net/myid", error="invalid_token", error_description="The authentication failed because of missing 'Authorization' header."

我不明白为什么它不想连接

更新:这可行,但有CURL

$authorization = "Authorization: Bearer ". $body_json->access_token;
    $ch = curl_init('https://management.azure.com/subscriptions/'.$subscriptionId.'/providers/Microsoft.Compute/virtualMachines?api-version=2017-12-01');

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    var_dump(json_decode($result));

更新: 列出虚拟机不起作用,它给我空的结果,我是否需要授予另一个访问权限才能执行此操作? https://management.azure.com/subscriptions/ '$ subscriptionId。'/提供商/ Microsoft.Compute / virtualMachines?API-版本= 2017年12月1日

1 个答案:

答案 0 :(得分:0)

请使用此代码请求:

 ['headers' => [
                'Authorization' => "Bearer " . $body_json->access_token
            ]