问题
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