Search code examples
azureazure-rest-apiazure-rbac

call azure management rest api through 'client credential' flow


I want to call some Azure management api, such as https://learn.microsoft.com/en-us/rest/api/authorization/role-assignments/create?tabs=HTTP#security

but in docs, they mention just 'implicit grant' oauth2 flow.

I want to use 'client credential' (with registered apps).


Solution

  • You can call Azure Management REST API using access token generated via client credentials flow.

    Register one Azure AD application and add API permissions as below:

    enter image description here

    Make sure to add proper RBAC role to above service principal before generating token.

    In my case, I assigned User Access Administrator role to the service principal under subscription like below:

    enter image description here

    Now, I generated access token using client credentials flow via Postman like this:

    POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
    grant_type:client_credentials
    client_id:<appID>
    client_secret:<secret>
    scope: https://management.azure.com/.default
    

    Response:

    enter image description here

    When I used this token to call Azure Management REST API, I got response successfully like below:

    PUT https://management.azure.com/subscriptions/<subID>/providers/Microsoft.Authorization/roleAssignments/<randomGUID>?api-version=2022-04-01
    
    {
      "properties": {
        "roleDefinitionId": "/subscriptions/<subID>/providers/Microsoft.Authorization/roleDefinitions/<roledefId>",
        "principalId": "userId",
        "principalType": "User"
      }
    }
    

    Response:

    enter image description here