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 Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,413 questions
OneDrive
OneDrive
A Microsoft file hosting and synchronization service.
966 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. CarlZhao-MSFT 40,221 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.