首页 > 解决方案 > TheNetworg oAuth2 to Microsoft Graph reports token expired while it's not

问题描述

I am trying to build a simple MS Graph API call to get familiar with Graph. However, I can't get it to work. MS Graph keeps giving the error that my token has expired, while it's not.

Code:

    <?php
require_once('C:\inetpub\site6\vendor\autoload.php');
// Using newest version of TheNetworg Oauth2

$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
    'clientId'          => '***************',
    'clientSecret'      => '**********',
    'redirectUri'       => 'https://app2.***/test.php'
]);

// Set to use v2 API, skip the line or set the value to Azure::ENDPOINT_VERSION_1_0 if willing to use v1 API
$provider->defaultEndPointVersion = TheNetworg\OAuth2\Client\Provider\Azure::ENDPOINT_VERSION_2_0;

$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);
//echo $baseGraphUri;

$provider->tenant = '*********.onmicrosoft.com'; //Azure AD ID
$provider->authWithResource;
$provider->scope = $baseGraphUri . '/.default';

$token = $provider->getAccessToken('client_credentials', ['scope' => $provider->scope]);
// echo $token;

// Set up our request to the API
  $ref= 'users/someuser@mytenant.com'; 
    $response = $provider->get($ref, $token, $headers = []);
  
 
    // Store the result as an object
    $result = json_decode( $response->getBody() ); 


?>

But I keep getting ended up with error:

PHP Fatal error: Uncaught League\OAuth2\Client\Provider\Exception\IdentityProviderException: Your access token has expired. Please renew it before submitting the request. in C:\inetpub\site6\vendor\thenetworg\oauth2-azure\src\Provider\Azure.php:394

What am I doing wrong? When I google the error, I get a lot of results telling that I am trying to access MS Graph with an Azure AD Graph token, but when I do echo $baseGraphUri; I really tells me graph.microsoft.com.

标签: phpazureoauth-2.0

解决方案


我发现了错误是什么。虽然我使用“$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);” ,该库仍连接到 Azure AD API,而不是 Microsoft Graph API。因此,它使用错误类型 (aud) 的令牌进行身份验证。

添加此行解决了问题:

$provider->urlAPI = 'https://graph.microsoft.com/';

推荐阅读