Passing a domain hint to Azure AD using ASP.NET Core 3.1 with Microsoft.Identity.Web

When building a single tenant app utilizing Azure AD for authentication, you may want to pass Azure AD a domain hint, especially in scenarios when Azure AD is federated with ADFS. This will tell Azure AD not to prompt the user for their UPN and will immediately redirect to your ADFS instance.

To accomplish this in ASP.NET Core 3.1 using Microsoft.Identity.Web, here’s an example from Startup.cs in the ConfigureServices function:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                var previous = options.Events.OnRedirectToIdentityProvider;
                options.Events.OnRedirectToIdentityProvider = async context =>
                {
                    if (previous != null)
                    {
                        await previous(context);
                    }
                    context.ProtocolMessage.DomainHint = "domain.com";
                };
            });

The important part is the configuring of the OpenIdConnectOptions block, where we add a handler for the OnRedirectToIdentityProvider event from OpenIdConnect. In this handler, we set the domain hint to the appropriate domain (replace domain.com with your domain).

Leave a comment