How to authenticate with Microsoft Graph API and retrieve OneDrive drive ID with PHP

不明 0 Reputation points
2023-12-05T05:20:36.2233333+00:00

I am creating a PHP script to back up my server configuration to OneDrive using Microsoft Graph API. I have created an app on Azure portal and selected "Accounts in any organizational directory (any Microsoft Entra ID tenant - multi-tenant)" and "personal Microsoft accounts (e.g. Skype, Xbox)" for authentication purposes. I want to retrieve the corresponding OneDrive for a user, but I'm getting an error that says:

The identity of the calling application could not be established.

I am using the following code:

$this->getGraphServiceClient()->users()->byUserId('user-id')->get()->wait(); 

What is the proper way to authenticate with Microsoft Graph API and retrieve the OneDrive drive ID for a specific user?

Microsoft 365 and Office OneDrive For business Windows
Microsoft Security Microsoft Graph
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. CarlZhao-MSFT 46,371 Reputation points
    2023-12-05T07:14:17.9666667+00:00

    Hi @不明

    To retrieve a specific user's OneDrive, you need to grant the calling app the Files.ReadWrite.All application permission and request an access token using the daemon-based client credentials flow.

    <?php
    use Microsoft\Graph\GraphServiceClient;
    use Microsoft\Kiota\Abstractions\ApiException;
    use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext;
    
    // Create an auth provider object. We're using the ClientCredentialContext library in this example. 
    $tokenRequestContext = new ClientCredentialContext(
        'TENANT_ID',
        'CLIENT_ID',
        'CLIENT_SECRET'
    );
    
    // Initialize the service client
    $graphServiceClient = new GraphServiceClient($tokenRequestContext);
    
    $result = $graphServiceClient->users()->byUserId('user-id')->drives()->get()->wait();
    
    

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.