Search code examples
azure-active-directorymicrosoft-graph-apivirtual-machineazure-rest-api

Permissions for listing virtual machines with Graph API


I am trying to use the request:

GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}?api-version=2020-12-01

From microsoft graph API:https://learn.microsoft.com/en-us/rest/api/compute/virtualmachines/get#code-try-0.

I created an app registration within the an AD subscription. When I try to use the oauth2 credentials associated with the app registration I receive a 401. I believe this is due to a permissions error. I tried using https://developer.microsoft.com/en-us/graph/graph-explorer, but I am unable to assume the app registration to simulate the request. Any insight as to why this might be happening or how to debug the issue would be very helpful


Solution

  • Your error is not a lack of permissions but the use of the wrong scope.

    The error is actually very simple, you need to grant Azure Service Management api permissions instead of MS graph permissions, and then you need to set the scope to: https://management.azure.com/user_impersonation.

    enter image description here

    enter image description here

    Next, use the auth code flow to obtain an access token.

    1. Request an authorization code in the browser.
    https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize?
    client_id={client id}
    &response_type=code
    &redirect_uri={redirect_uri}
    &response_mode=query
    &scope=https://management.azure.com/user_impersonation
    &state=12345
    
    1. Redeem token.

    enter image description here

    Call api:

    enter image description here

    Please note that do not use graph-explorer test, because you are not calling MS graph api, you can use postman.