Home > Back-end >  Why am I Getting "401 Unauthorized" for Microsoft Graph API Call?
Why am I Getting "401 Unauthorized" for Microsoft Graph API Call?

Time:12-29

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 protected]/messages/xxxxxxxxxxxxx==')->execute());
} catch (\Exception $e) {
    print $e->getMessage();
}

Both tenants have these permissions granted: enter image description here

CodePudding user response:

401 Unauthorized error: Is your token valid?

Make sure that your application is presenting a valid access token to Microsoft Graph as part of the request. This error often means that the access token may be missing in the HTTP authenticate request header or that the token is invalid or has expired. We strongly recommend that you use the Microsoft Authentication Library (MSAL) for access token acquisition. Additionally, this error may occur, if you try to use a delegated access token granted to a personal Microsoft account, to access an API that only supports work or school accounts (organizational accounts).

You can always leverage jwt.ms to check claims on your token. Use this and check if you have the necessary permissions to call an API endpoint.

  • Related