Search code examples
azure-active-directorymicrosoft-graph-api

Microsoft Graph API add scp or roles claim


This is how I get the access token with PHP microsoft/graph lib

$token_url = "https://login.microsoftonline.com/{$tenant_id}/oauth2/v2.0/token";

$data = [
    'grant_type' => 'client_credentials',
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'scope' => 'https://graph.microsoft.com/.default',

];

$options = [
    CURLOPT_URL => $token_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($data)
];

$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);

$response_data = json_decode($response, true);
$accessToken = $response_data['access_token'];

How can I add scp or roles claim for the access token?

Postman App API Permissions


Solution

  • Note that, client credentials flow only works with permissions of Application type. The error occurred as you are using Delegated permissions.

    I registered one Azure AD application and added Sites.Read.All permission of Delegated type:

    enter image description here

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

    POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
    grant_type:client_credentials
    client_id: appId
    client_secret: secret 
    scope: https://graph.microsoft.com/.default
    

    Response:

    enter image description here

    When I used this token to list sites, I got same error like below:

    GET https://graph.microsoft.com/v1.0/sites?search=*
    

    Response:

    enter image description here

    To resolve the error, you need to add Sites.Read.All permission of Application type and make sure to grant admin consent to it:

    enter image description here

    Now, generate the token again using client credentials flow after granting consent to above permission.

    To check whether the token has permission or not, you can decode it by pasting it in jwt.ms site and find roles claim:

    enter image description here

    When I used this token to list sites by running below query again, I got response successfully:

    GET https://graph.microsoft.com/v1.0/sites?search=*
    

    Response:

    enter image description here