Search code examples
phpmicrosoft-graph-api

Why am I Getting "401 Unauthorized" for Microsoft Graph API Call?


I created the app in Tenant A and added it to Tenant B. I have granted the permissions in both tenants. Why am I getting this response every time I make an API call to the app?

resulted in a `401 Unauthorized` response: {"error":{"code":"NoPermissionsInAccessToken","message":"The token contains no permissions, or permissions can not be un (truncated...)

Here is the PHP request that I'm making (I am using the client id and client secret from the app in Tenant A):

<?php

use League\OAuth2\Client\Provider\Exception\IdentityProviderException;

use Microsoft\Graph\Graph;

$guzzle = new \GuzzleHttp\Client();

$tenantId = 'common';
$clientId = 'ccc-ddd-fff';
$clientSecret = 'xxx-yyy-zzz';

$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';

try {
    $token = json_decode($guzzle->post($url, [
        'form_params' => [
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'resource' => 'https://graph.microsoft.com/',
            'grant_type' => 'client_credentials',
        ],
    ])->getBody()->getContents());

    $accessToken = $token->access_token;

} catch (\Exception $e) {
    print $e->getMessage();
}

$graph = new Graph();
$graph->setAccessToken($accessToken);

try {
    print_r($graph->createRequest("GET", '/users/email@email.com/messages/xxxxxxxxxxxxx==')->execute());
} catch (\Exception $e) {
    print $e->getMessage();
}

Both tenants have these permissions granted: Permissions in Tenant A and B


Solution

  • What I needed to do was prompt the Microsoft admin to grant permissions using a link similar to this one. Merely adding the enterprise from the Microsoft

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?scope=offline_access+openid+profile+User.Read+Mail.ReadWrite+Mail.Send
    &response_type=code
    &client_id=a62b0808-2b1f-4efc-a3d6-ad1223dc06a9
    &redirect_uri=https://myurl/blah.html
    &response_mode=query