从Microsoft Graph PHP SDK v2获取AccessToken
获取Microsoft Graph PHP SDK连接的AccessToken
你可以通过代码中已创建的GraphPhpLeagueAuthenticationProvider实例获取当前使用的AccessToken,具体实现如下:
- 调用
authProvider的getAuthorizationTokenAsync()方法,该方法返回Promise对象,通过wait()同步获取结果 - 从返回的token对象中提取
access_token值
修改后的代码示例:
$tokenRequestContext = new AuthorizationCodeContext( 'tenantId', 'clientId', 'clientSecret', 'authCode', 'redirectUri' ); $authProvider = new GraphPhpLeagueAuthenticationProvider($tokenRequestContext, $scopes); $requestAdapter = new GraphRequestAdapter($authProvider); $graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes, requestAdapter: $requestAdapter); // 获取当前有效的AccessToken $tokenResult = $authProvider->getAuthorizationTokenAsync()->wait(); $accessToken = $tokenResult->getToken(); // 部分场景下可直接访问属性:$tokenResult->access_token,取决于Token对象实现 $user = $graphServiceClient->me()->get()->wait();
说明:
getAuthorizationTokenAsync()会自动处理token刷新逻辑,确保返回的是当前可用的有效AccessToken- 若在异步环境中使用,可直接使用Promise对象,无需调用
wait()
内容的提问来源于stack exchange,提问作者M Biniek
相关产品推荐
相关产品推荐

