MS Graph Access Token Refresh with GuzzleHttp

1.1k views Asked by At

I'm trying to refresh an access token using a refresh token on MS graph platform. To do this I've been inspired by this documentation from Microsoft: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow I've been successful in retrieving a new token with Postman by forging the request and replacing the needed key=>value with my app-specific values. When I dump the code using the PHP Guzzle format I get this:

<?php
$client = new Client();
$headers = [
  'Content-Type' => 'application/x-www-form-urlencoded',
];
$options = [
'form_params' => [
  'client_id' => config('config.microsoft.clientId'),
  'scope' => 'user.read',
  'redirect_uri' => 'http://localhost:8000/callback',
  'grant_type' => 'refresh_token',
  'client_secret' => config('config.microsoft.ClientSecret'),
  'refresh_token' => config('config.microsoft.RefToken')
]];
$request = new Request('POST', 'https://login.microsoftonline.com/common/oauth2/v2.0/token', $headers);
$res = $client->sendAsync($request, $options)->wait();
echo $res;

I add copied this code to my app but when I run it here's what I got:

    GuzzleHttp\Psr7\Response {#1514 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:13 [▶]
  -headerNames: array:13 [▶]
  -protocol: "1.1"
  -stream: GuzzleHttp\Psr7\Stream {#1524 ▼
    -stream: stream resource @13 ▶}
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}

Note that I get a 200 status code which means that the request is a success but nothing is retrieved from MS website. I do receive new token info with Postman why do I receive nothing in my PHP app with the exact same copy-pasting of the request. Is this possible that MS is shy to respond to my Guzzle client? BTW the same export also works in cURL.

EDIT:

I tried with "PHP cURL" and "PHP - HTTP_Request2" and these methods both work in my app. for now I'll stick with PHP-HTTP_Request2. If anyone have and idea why I retrive nothing with GuzzleHTTP please let me know.

1

There are 1 answers

0
vicky kumar On

Thanks for reaching out to us ,as we can see in the code you are using wait() function instead of await() , could you please correct and try again?

you can also see similar questions - How can I use Guzzle to send a POST request in JSON?

ref docs- https://docs.guzzlephp.org/en/latest/psr7.html#responses let us know if that works. Thanks