askwizard
askwizard

Reputation: 127

How to pass access token stored in variable in PHP to an array

I was able to find the access token from Azure

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://login.microsoftonline.com/12baf------------/oauth2/token',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => 'grant_type=client_credentials&client_id=XXXXX-57b4-XXXXb-XXXX-13ca1f5eec6e&client_secret=XXXXX&resource=https%3A%2F%2Fmanagement.azure.com%2F',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/x-www-form-urlencoded',
    'Cookie: fpc=AlXXXXXXXXpKm43KbQ52MOkk8jRRAQAAAI8Us9cOAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=prod'
  ),
));

$json = curl_exec($curl);
$data=json_decode($json,true);
curl_close($curl);
$token=$data['access_token'];

But when I am trying to pass the variable in CURLOPT_HTTPHEADER it's showing an invalid token.

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://management.azure.com/subscriptions/XXXXXXX-1faf-4756-a709-1af49be58e56/resourcegroups?api-version=2020-06-01',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer '$token'
  ),
));

$response = curl_exec($curl);
echo $response
?>

How can I pass the token in the above array or there is an easy way to do it? Can anyone please help here.

Upvotes: 0

Views: 884

Answers (1)

askwizard
askwizard

Reputation: 127

I able to resolve it as below

$authorization = "Authorization: Bearer ".$token; 

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://management.azure.com/subscriptions/xxxxxxx-4756-a709-1af49be58e56/resourcegroups?api-version=2020-06-01',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json' , $authorization)
  ),
);

$response = curl_exec($curl);
echo $response
?>

Upvotes: 1

Related Questions