Search code examples
azureoauth-2.0azure-functionsazure-resource-managerazure-rest-api

How to access the Microsoft Resource Management API as a service using OAuth2.0


I am developing a time-triggered service that fetches data from various API's and writes it to a database. One of the API's I need to access is the Microsoft Resource Management API. However, the problem is that its endpoints all mention the OAuth2.0 explicit grant flow- which requires a user to log in. Since I am creating a automated service, I cannot use that flow.

For example, the list resource group endpoint (https://learn.microsoft.com/en-us/rest/api/resources/resource-groups/list) mentions the Oauth2 implicit grant flow with the user_impersonation scope:

https://i.sstatic.net/0XmIW.png

Is it even possible to get data from this API as a service, and if so, how would I go about doing that? Is there any other way I could get a list of resource groups and resources from the Azure platform?

I do succesfully utilize the OAuth2.0 client credientials grant flow to authenticate with the Graph API as a service, but that does not seem possible here.


Solution

  • To call Azure Management REST API, you need to generate access token with scope as https://management.azure.com/.default.

    I registered one Azure AD application and added API permission as below:

    enter image description here

    Make sure to add proper RBAC role to above service principal under subscription.

    In my case, I added Reader role to the service principal under subscription like below:

    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://management.azure.com/.default
    

    Response:

    enter image description here

    When I used this access token to call below Management API query, I got list of resource groups successfully in response like this:

    GET https://management.azure.com/subscriptions/<subID>/resourcegroups?api-version=2021-04-01
    

    Response: enter image description here