I have an ASP.NET Core MVC app using the Microsoft Identity Platform for authentication, currently set up for multi-tenancy with one app registration. I want to extend this to support two separate app registrations (for two different tenants) and allow users from both tenants to authenticate, selecting the appropriate app registration dynamically based on the tenant ID.
How can I configure Program.cs to achieve this?
Current appsettings.json:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "******.onmicrosoft.com",
"TenantId": "**********",
"ClientId": "**********",
"CallbackPath": "/signin-oidc",
"ClientSecret": "**********"
},
"AllowedTenants": [ "**********", "**********" ],
"DownstreamApi": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "User.Read"
}
Desired appsettings.json with two app registrations:
"AzureAdOne": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "******.onmicrosoft.com",
"TenantId": "**********",
"ClientId": "**********",
"CallbackPath": "/signin-oidc",
"ClientSecret": "**********"
},
"AzureAdTwo": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "******.onmicrosoft.com",
"TenantId": "**********",
"ClientId": "**********",
"CallbackPath": "/signin-oidc",
"ClientSecret": "**********"
},
"AllowedTenants": [ "**********", "**********" ],
"DownstreamApi": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "User.Read"
}
current Program.cs
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
// Sign-in users with the Microsoft identity platform
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAd", options);
options.Events.OnTokenValidated = async context =>
{
string tenantId = context.SecurityToken.Claims.FirstOrDefault(x => x.Type == "tid" || x.Type == "http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
var allowedTenants = Configuration.GetSection("AllowedTenants").Get<string[]>().ToList();
if (string.IsNullOrWhiteSpace(tenantId) || !allowedTenants.Contains(tenantId))
throw new UnauthorizedAccessException("Unable to get tenantId from token or the tenant is not authorized.");
};
})
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
In the login partial, users can select their company:
<a class="dropdown-item" href="/MicrosoftIdentity/Account/SignIn?scheme=TenantIdOne">Company One</a>
<a class="dropdown-item" href="/MicrosoftIdentity/Account/SignIn?scheme=TenantIdTwo">Company Two</a>
What’s the best way to implement this in Program.cs to dynamically select the app registration based on the tenant?




