Building an ASP.Net Core multi-tenant web app on .Net 6 with Azure AD authentication and permissions to access the MS Graph API as the app.
All works well but I'm confused.
To add Azure AD authentication, this code is added to my Program.cs to find the necessary application credentials:
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
For local development I can store the app credentials in an appsettings file or environment variables. I prefer environment variables:
"AzureAd__ClientId": <my-clientId>
"AzureAd__ClientSecret": <my-clientsecret>
"AzureAd__TenantId": "organizations"
This works fine together with the configuration for authentication of a multi-tenant in my appsettings
"AzureAd":
{
"Instance": "https://login.microsoftonline.com/",
"Domain": <mydomain>,
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath": "/signout-callback-oidc"
}
(I can change the AzureAd
prefix in both locations.)
So far so good.
Now to give this app permissions to access MS Graph as the app identity:
- Configure the necessary Application permission in the Azure Portal for the App to access MS Graph
- Add Nuget package
Microsoft.Identity.Web.MicrosoftGraph
- In code, create a client that accesses the MS Graph as the app:
var credential = new DefaultAzureCredential();
var token = credential.GetToken(
new Azure.Core.TokenRequestContext(
new[] { "https://graph.microsoft.com/.default" }));
var graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
return Task.CompletedTask;
}));
This code however does not pick up the credentials already stored in configuration. Also not with other variations of the Azure.Core.TokenCredential
, e.g.
var credential = new EnvironmentCredential();
According to the documentation of the EnvironmentVariables class, I have to create a second set of environment variables that hold the app credentials for this to work, namely as AZURE_CLIENT_ID
, AZURE_CLIENT_SECRET
, and AZURE_TENANT_ID
.
I know find myself with two different sets of environment variables holding the same values.
Moreover, multi-tenant authentication requires AzureAd__TenantId=organizations
and accessing the MS Graph API as the app requires AZURE_TENANT_ID=<my-tenant-id>
Is this correct? Or is there a better way that does not require storing the same settings twice?