Search code examples
azureazure-active-directoryjwtmicrosoft-graph-apiazure-app-registration

Get Access Token from Microsoft Graph for ClientId with delegated permissions


I wanted to use a high-level PowerShell method to get authorization for a ClientId (app registration) to access a scope using my Azure user's delegated permissions.

I can do that manually by requesting a device code at https://login.microsoftonline.com/$TenantId/oauth2/v2.0/devicecode and then a token at "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token", like in my other question, but I'd prefer to have a more reliable method.

Since MSAL.PS module is not maintained by Microsoft since 2023, I tried Microsoft.Graph module:

$tenantId = '00000000-0000-0000-0000-000000000000'
$appId = '00000000-0000-0000-0000-000000000000'
$serviceId = '00000000-0000-0000-0000-000000000000'

Install-Module Microsoft.Graph -Scope CurrentUser -Repository PSGallery
$null = Connect-MgGraph `
    -ClientId $appId -TenantId $tenantId `
    -Scopes 'api://$serviceId/MyData.FullControl.All offline_access' `
    -UseDeviceCode -NoWelcome
# print current context
Get-MgContext

$headers = @{
    'Accept' = "application/json"
    # 'Authorization' = "Bearer $sometoken" # can't get token from previous authentication
}
Invoke-MgGraphRequest -Method GET `
    -Uri 'https:///my-service-endpoint.azurewebsites.net/api/data/01' `
    -ContentType "application/json"

However the response is 401 unauthorized.


Solution

  • Note that, Microsoft.Graph PowerShell module does not expose the access token directly and it is specifically designed for interacting with Microsoft Graph API not custom API.

    Alternatively, make use of Az PowerShell module to get access token for custom API with user's delegated permissions.

    Initially, I exposed an API with new scope named MyData.FullControl.All in app registration like this:

    enter image description here

    Make sure to add Microsoft Azure PowerShell (1950a258-227b-4e31-a9cf-717495945fc2) in Authorized client applications tab of service app as below:

    enter image description here

    Now, I ran below Az PowerShell commands in Azure Cloud Shell and got the access token successfully like this:

    $tenantId = 'tenantId'  
    Connect-AzAccount -Tenant $tenantId -UseDeviceAuthentication 
    (Get-AzAccessToken -ResourceUrl "api://e32xxxxxxx").Token
    

    Response:

    enter image description here

    To confirm that, you can decode this token in jwt.ms website and check scp claim:

    enter image description here

    If the use case is to acquire token from ClientId (app registration) with user's delegated permissions, the only way is to manually acquire token as of now like the other question.