I am building a web app and want users to be able to authenticate with Azure AD. The organisation I am working for has two Azure AD Tenants, and they have created an App Registration in each. Both App Registrations are set as Single Tenant not Multitenant because we do not want users from other Azure AD Tenants to be able to authenticate and a Multitenant app registration allows users from any Azure AD tenant to authenticate. For clarity, I am working with multiple Single Tenant app registrations, not a single Multitenant app registration.
I have got working code for authenticating with a single Azure AD tenant (shown below) but this involves specifying the TenantId and ClientId in appsettings.json
, so they cannot be changed after app startup. I would like to specify the TenantId and ClientId at the point of issuing the authentication challenge, so I can present the user with a choice of which Tenant they want to authenticate with - i.e. by the time I call return Challenge(...);
in my controller I would know the TenantId and ClientId, but at the point of app startup I would have multiple possibilities.
I haven't found any examples of this approach online, so I don't know whether or not it's possible using Microsoft.Identity.Web
. How can I authenticate a user with Azure AD without specifying the TenantId and ClientId during app startup?
In my controller the relevant action contains this code:
return Challenge(
new AuthenticationProperties
{
RedirectUri = callbackPath, // this is built up earlier in the method
Items =
{
new KeyValuePair<string, string>("LoginProvider", Microsoft.Identity.Web.Constants.AzureAd)
}
},
Microsoft.Identity.Web.Constants.AzureAd);
Within appsettings.json
I have a section which includes the tenant and client IDs (redacted for this question, but the file does include the real IDs):
"AzureAD": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "********-****-****-****-************",
"ClientId": "********-****-****-****-************",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath ": "/signout-callback-oidc"
}
In code called from Startup.cs
I have the following code which uses the configuration from appsettings.json
.
services
.AddAuthentication()
.AddIdentityServerAuthentication(options =>
{
options.Authority = authConfig.Authority;
options.RequireHttpsMetadata = true;
});
// This uses the "AzureAD" section from appsettings.json
services.AddMicrosoftIdentityWebAppAuthentication(configuration, openIdConnectScheme: Microsoft.Identity.Web.Constants.AzureAd);
services.Configure<OpenIdConnectOptions>(Microsoft.Identity.Web.Constants.AzureAd, options => options.SignInScheme = IdentityConstants.ExternalScheme);