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?
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);
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:
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.
And make sure to grant the API permissions:
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);