Search code examples
c#azureazure-active-directoryazure-functions

How to get ResourceId from AAD application


I want to fetch the Access Token from AAD application using below snippet.

var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { ResourceId + "/.default" }) { }
);

I have created AAD application on Azure portal, How to get ResourceId from the AAD application?

enter image description here


Solution

  • Note that: Resource ID depends on the Azure resource you want to authenticate the Azure AD Application (Microsoft Graph, Web Api etc).

    For sample, I passed https://graph.microsoft.com as resourceId to authenticate Microsoft Graph API.

    using Azure.Core;
    using Azure.Identity;
    
    // Define the resource ID for the Azure AD application you want to access.
    string resourceId = "https://graph.microsoft.com";
    
    var tokenCredential = new DefaultAzureCredential();
    
    var accessToken = await tokenCredential.GetTokenAsync(
        new TokenRequestContext(scopes: new string[] { resourceId + "/.default" })
    );
    
    Console.WriteLine(accessToken.Token);
    

    enter image description here

    I agree with @juunas, if you want to authenticate the web Api you can pass resourceId as the ClientID or the API URL of the Azure AD Application like below:

    enter image description here

    Note that: To fetch the access token for web Api, you must add Microsoft Azure CLI with client ID 04b07795-8ddb-461a-bbee-02f9e1bf7b46 as the Authorized client application.

    Go to the Azure AD App -> Expose an API -> Add client application with 04b07795-8ddb-461a-bbee-02f9e1bf7b46 and check the scope.

    enter image description here

    And make sure to grant the API permissions:

    enter image description here

    using Azure.Core;
    using Azure.Identity;
    
    
    // Define the resource ID for the Azure AD application you want to access.
    string resourceId = "api://ClientID";
    
    var tokenCredential = new DefaultAzureCredential();
    
    var accessToken = await tokenCredential.GetTokenAsync(
        new TokenRequestContext(scopes: new string[] { resourceId + "/.default" })
    );
    
    Console.WriteLine(accessToken.Token);
    

    enter image description here