guzzle on azure to get all virtual hosts

三世轮回 提交于 2019-12-11 18:27:41

问题


I have working code on Postman and I can get all virtual hosts, but when Im doing on the PHP with Guzzle it gives me trouble. First part of code I get it where I get bearer token, but then to get list of virtual hosts it gives me error.

here is my code

$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
    ]);

and error:

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

I don't see why it doesn't want to connect

UPDATE: THIS WORKS, but with 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));

UPDATE: listing Virtual machines don't work, it gives me empty results, do I need to grant another access to be able to do this? https://management.azure.com/subscriptions/'.$subscriptionId.'/providers/Microsoft.Compute/virtualMachines?api-version=2017-12-01


回答1:


Please use this code to request:

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


来源:https://stackoverflow.com/questions/49520538/guzzle-on-azure-to-get-all-virtual-hosts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!