Peter VARGA
Peter VARGA

Reputation: 5186

Onedrive GRAPH API - 403 when getting user's OneDrive

I am trying to get the user's OneDrive information according to this documentation with this URL:
https://graph.microsoft.com/v1.0/users/[email protected]/drive

I get 403 error. The user has a Business account, the credentials are OK. What else can I check in order to get from the user its OneDrive?

(
    [status] => 500
    [error] => Error fetching files: file_get_contents(https://[email protected]/drive): Failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden

)

I need this information in order to read the content of the user's OneDrive directories.


UPDATE: As requested, the permissions

enter image description here


The authentication flow - I removed the error checking code. It returns then the content of the array item 'access_token'.

public static function authenticate($clientId, $tenantId, $clientSecret) {
    $url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";

    $postData = http_build_query([
        'client_id'     => $clientId,
        'scope'         => 'https://graph.microsoft.com/.default',
        'client_secret' => $clientSecret,
        'grant_type'    => 'client_credentials',
    ]);

    $options = [
        'http' => [
            'header'  => "Content-Type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => $postData,
        ],
    ];

    $context = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

    ....

    $body = json_decode($response, true);

    ...

    return $body['access_token'];
}

UPDATE: The user's overview

enter image description here

Upvotes: 0

Views: 98

Answers (1)

Sridevi
Sridevi

Reputation: 22552

The error occurred as you granted permissions of Delegated type but using client credentials flow for token generation that works only with Application type permission.

To resolve the error, make sure to grant Files.Read.All permission of Application type with admin consent like this:

enter image description here

Now, I generated access token using client credentials flow with below parameters:

POST https://login.microsoftonline.com/tenantID/oauth2/v2.0/token

grant_type:client_credentials
client_id: appID
client_secret: secretValue
scope: https://graph.microsoft.com/.default

enter image description here

When I used this token to retrieve drive of user, I got response like this:

GET https://graph.microsoft.com/v1.0/users/[email protected]/drive

Response:

enter image description here

These are the files and folders present in my OneDrive account:

enter image description here

To retrieve these OneDrive files, you can make use of below Graph API call:

GET https://graph.microsoft.com/v1.0/users/[email protected]/drive/root/children

Response:

enter image description here

Upvotes: 2

Related Questions