Example #1
0
        private static void AddMicrosoftIdentityWebAppInternal(
            AuthenticationBuilder builder,
            Action <MicrosoftIdentityOptions> configureMicrosoftIdentityOptions,
            Action <CookieAuthenticationOptions>?configureCookieAuthenticationOptions,
            string openIdConnectScheme,
            string?cookieScheme,
            bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents,
            string?displayName)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (configureMicrosoftIdentityOptions == null)
            {
                throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions));
            }

            builder.Services.Configure(openIdConnectScheme, configureMicrosoftIdentityOptions);
            builder.Services.AddHttpClient();

            if (!string.IsNullOrEmpty(cookieScheme))
            {
                Action <CookieAuthenticationOptions> emptyOption = option => { };
                builder.AddCookie(cookieScheme, configureCookieAuthenticationOptions ?? emptyOption);
            }

            builder.Services.TryAddSingleton <MicrosoftIdentityIssuerValidatorFactory>();
            builder.Services.TryAddSingleton <ILoginErrorAccessor>(ctx =>
            {
                // ITempDataDictionaryFactory is not always available, so we don't require it
                var tempFactory = ctx.GetService <ITempDataDictionaryFactory>();
                var env         = ctx.GetService <IHostEnvironment>(); // ex. Azure Functions will not have an env.

                if (env != null)
                {
                    return(TempDataLoginErrorAccessor.Create(tempFactory, env.IsDevelopment()));
                }
                else
                {
                    return(TempDataLoginErrorAccessor.Create(tempFactory, false));
                }
            });

            if (subscribeToOpenIdConnectMiddlewareDiagnosticsEvents)
            {
                builder.Services.AddSingleton <IOpenIdConnectMiddlewareDiagnostics, OpenIdConnectMiddlewareDiagnostics>();
            }

            if (AppServicesAuthenticationInformation.IsAppServicesAadAuthenticationEnabled)
            {
                builder.Services.AddAuthentication(AppServicesAuthenticationDefaults.AuthenticationScheme)
                .AddAppServicesAuthentication();
                return;
            }

            if (!string.IsNullOrEmpty(displayName))
            {
                builder.AddOpenIdConnect(openIdConnectScheme, displayName: displayName, options => { });
            }
            else
            {
                builder.AddOpenIdConnect(openIdConnectScheme, options => { });
            }

            builder.Services.AddOptions <OpenIdConnectOptions>(openIdConnectScheme)
            .Configure <IServiceProvider, IOptionsMonitor <MergedOptions>, IOptionsMonitor <MicrosoftIdentityOptions>, IOptions <MicrosoftIdentityOptions> >((
                                                                                                                                                                 options,
                                                                                                                                                                 serviceProvider,
                                                                                                                                                                 mergedOptionsMonitor,
                                                                                                                                                                 msIdOptionsMonitor,
                                                                                                                                                                 msIdOptions) =>
            {
                MicrosoftIdentityBaseAuthenticationBuilder.SetIdentityModelLogger(serviceProvider);

                MergedOptions mergedOptions = mergedOptionsMonitor.Get(openIdConnectScheme);

                MergedOptions.UpdateMergedOptionsFromMicrosoftIdentityOptions(msIdOptions.Value, mergedOptions);
                MergedOptions.UpdateMergedOptionsFromMicrosoftIdentityOptions(msIdOptionsMonitor.Get(openIdConnectScheme), mergedOptions);

                MergedOptionsValidation.Validate(mergedOptions);
                PopulateOpenIdOptionsFromMergedOptions(options, mergedOptions);

                var b2cOidcHandlers = new AzureADB2COpenIDConnectEventHandlers(
                    openIdConnectScheme,
                    mergedOptions,
                    serviceProvider.GetRequiredService <ILoginErrorAccessor>());

                if (!string.IsNullOrEmpty(cookieScheme))
                {
                    options.SignInScheme = cookieScheme;
                }

                if (string.IsNullOrWhiteSpace(options.Authority))
                {
                    options.Authority = AuthorityHelpers.BuildAuthority(mergedOptions);
                }

                // This is a Microsoft identity platform web app
                options.Authority = AuthorityHelpers.EnsureAuthorityIsV2(options.Authority);

                // B2C doesn't have preferred_username claims
                if (mergedOptions.IsB2C)
                {
                    options.TokenValidationParameters.NameClaimType = ClaimConstants.Name;
                }
                else
                {
                    options.TokenValidationParameters.NameClaimType = ClaimConstants.PreferredUserName;
                }

                // If the developer registered an IssuerValidator, do not overwrite it
                if (options.TokenValidationParameters.ValidateIssuer && options.TokenValidationParameters.IssuerValidator == null)
                {
                    // If you want to restrict the users that can sign-in to several organizations
                    // Set the tenant value in the appsettings.json file to 'organizations', and add the
                    // issuers you want to accept to options.TokenValidationParameters.ValidIssuers collection
                    MicrosoftIdentityIssuerValidatorFactory microsoftIdentityIssuerValidatorFactory =
                        serviceProvider.GetRequiredService <MicrosoftIdentityIssuerValidatorFactory>();

                    options.TokenValidationParameters.IssuerValidator =
                        microsoftIdentityIssuerValidatorFactory.GetAadIssuerValidator(options.Authority).Validate;
                }

                // Avoids having users being presented the select account dialog when they are already signed-in
                // for instance when going through incremental consent
                var redirectToIdpHandler = options.Events.OnRedirectToIdentityProvider;
                options.Events.OnRedirectToIdentityProvider = async context =>
                {
                    var loginHint = context.Properties.GetParameter <string>(OpenIdConnectParameterNames.LoginHint);
                    if (!string.IsNullOrWhiteSpace(loginHint))
                    {
                        context.ProtocolMessage.LoginHint = loginHint;

                        context.ProtocolMessage.SetParameter(Constants.XAnchorMailbox, $"{Constants.Upn}:{loginHint}");
                        // delete the login_hint from the Properties when we are done otherwise
                        // it will take up extra space in the cookie.
                        context.Properties.Parameters.Remove(OpenIdConnectParameterNames.LoginHint);
                    }

                    var domainHint = context.Properties.GetParameter <string>(OpenIdConnectParameterNames.DomainHint);
                    if (!string.IsNullOrWhiteSpace(domainHint))
                    {
                        context.ProtocolMessage.DomainHint = domainHint;

                        // delete the domain_hint from the Properties when we are done otherwise
                        // it will take up extra space in the cookie.
                        context.Properties.Parameters.Remove(OpenIdConnectParameterNames.DomainHint);
                    }

                    context.ProtocolMessage.SetParameter(Constants.ClientInfo, Constants.One);
                    context.ProtocolMessage.SetParameter(Constants.TelemetryHeaderKey, IdHelper.CreateTelemetryInfo());

                    // Additional claims
                    if (context.Properties.Items.TryGetValue(OidcConstants.AdditionalClaims, out var additionClaims))
                    {
                        context.ProtocolMessage.SetParameter(
                            OidcConstants.AdditionalClaims,
                            additionClaims);
                    }

                    if (mergedOptions.IsB2C)
                    {
                        // When a new Challenge is returned using any B2C user flow different than susi, we must change
                        // the ProtocolMessage.IssuerAddress to the desired user flow otherwise the redirect would use the susi user flow
                        await b2cOidcHandlers.OnRedirectToIdentityProvider(context).ConfigureAwait(false);
                    }

                    await redirectToIdpHandler(context).ConfigureAwait(false);
                };

                if (mergedOptions.IsB2C)
                {
                    var remoteFailureHandler       = options.Events.OnRemoteFailure;
                    options.Events.OnRemoteFailure = async context =>
                    {
                        // Handles the error when a user cancels an action on the Azure Active Directory B2C UI.
                        // Handle the error code that Azure Active Directory B2C throws when trying to reset a password from the login page
                        // because password reset is not supported by a "sign-up or sign-in user flow".
                        await b2cOidcHandlers.OnRemoteFailure(context).ConfigureAwait(false);

                        await remoteFailureHandler(context).ConfigureAwait(false);
                    };
                }

                if (subscribeToOpenIdConnectMiddlewareDiagnosticsEvents)
                {
                    var diagnostics = serviceProvider.GetRequiredService <IOpenIdConnectMiddlewareDiagnostics>();

                    diagnostics.Subscribe(options.Events);
                }
            });
        }
        private static void AddMicrosoftIdentityWebApiImplementation(
            AuthenticationBuilder builder,
            Action <JwtBearerOptions> configureJwtBearerOptions,
            Action <MicrosoftIdentityOptions> configureMicrosoftIdentityOptions,
            string jwtBearerScheme,
            bool subscribeToJwtBearerMiddlewareDiagnosticsEvents)
        {
            builder.AddJwtBearer(jwtBearerScheme, configureJwtBearerOptions);
            builder.Services.Configure(jwtBearerScheme, configureMicrosoftIdentityOptions);

            builder.Services.AddHttpContextAccessor();
            builder.Services.AddHttpClient();
            builder.Services.TryAddSingleton <MicrosoftIdentityIssuerValidatorFactory>();
            builder.Services.AddRequiredScopeAuthorization();
            builder.Services.AddRequiredScopeOrAppPermissionAuthorization();
            builder.Services.AddOptions <AadIssuerValidatorOptions>();

            if (subscribeToJwtBearerMiddlewareDiagnosticsEvents)
            {
                builder.Services.AddTransient <IJwtBearerMiddlewareDiagnostics, JwtBearerMiddlewareDiagnostics>();
            }

            // Change the authentication configuration to accommodate the Microsoft identity platform endpoint (v2.0).
            builder.Services.AddOptions <JwtBearerOptions>(jwtBearerScheme)
            .Configure <IServiceProvider, IOptionsMonitor <MergedOptions>, IOptionsMonitor <MicrosoftIdentityOptions>, IOptions <MicrosoftIdentityOptions> >((
                                                                                                                                                                 options,
                                                                                                                                                                 serviceProvider,
                                                                                                                                                                 mergedOptionsMonitor,
                                                                                                                                                                 msIdOptionsMonitor,
                                                                                                                                                                 msIdOptions) =>
            {
                MicrosoftIdentityBaseAuthenticationBuilder.SetIdentityModelLogger(serviceProvider);
                MergedOptions mergedOptions = mergedOptionsMonitor.Get(jwtBearerScheme);
                MergedOptions.UpdateMergedOptionsFromJwtBearerOptions(options, mergedOptions);
                MergedOptions.UpdateMergedOptionsFromMicrosoftIdentityOptions(msIdOptions.Value, mergedOptions);
                MergedOptions.UpdateMergedOptionsFromMicrosoftIdentityOptions(msIdOptionsMonitor.Get(jwtBearerScheme), mergedOptions);

                MergedOptionsValidation.Validate(mergedOptions);

                if (string.IsNullOrWhiteSpace(options.Authority))
                {
                    options.Authority = AuthorityHelpers.BuildAuthority(mergedOptions);
                }

                // This is a Microsoft identity platform web API
                options.Authority = AuthorityHelpers.EnsureAuthorityIsV2(options.Authority);

                if (options.TokenValidationParameters.AudienceValidator == null &&
                    options.TokenValidationParameters.ValidAudience == null &&
                    options.TokenValidationParameters.ValidAudiences == null)
                {
                    RegisterValidAudience registerAudience = new RegisterValidAudience();
                    registerAudience.RegisterAudienceValidation(
                        options.TokenValidationParameters,
                        mergedOptions);
                }

                // If the developer registered an IssuerValidator, do not overwrite it
                if (options.TokenValidationParameters.ValidateIssuer && options.TokenValidationParameters.IssuerValidator == null)
                {
                    // Instead of using the default validation (validating against a single tenant, as we do in line of business apps),
                    // we inject our own multi-tenant validation logic (which even accepts both v1.0 and v2.0 tokens)
                    MicrosoftIdentityIssuerValidatorFactory microsoftIdentityIssuerValidatorFactory =
                        serviceProvider.GetRequiredService <MicrosoftIdentityIssuerValidatorFactory>();

                    options.TokenValidationParameters.IssuerValidator =
                        microsoftIdentityIssuerValidatorFactory.GetAadIssuerValidator(options.Authority).Validate;
                }

                // If you provide a token decryption certificate, it will be used to decrypt the token
                if (mergedOptions.TokenDecryptionCertificates != null)
                {
                    DefaultCertificateLoader.UserAssignedManagedIdentityClientId = mergedOptions.UserAssignedManagedIdentityClientId;
                    IEnumerable <X509Certificate2?> certificates          = DefaultCertificateLoader.LoadAllCertificates(mergedOptions.TokenDecryptionCertificates);
                    IEnumerable <X509SecurityKey> keys                    = certificates.Select(c => new X509SecurityKey(c));
                    options.TokenValidationParameters.TokenDecryptionKeys = keys;
                }

                if (options.Events == null)
                {
                    options.Events = new JwtBearerEvents();
                }

                // When an access token for our own web API is validated, we add it to MSAL.NET's cache so that it can
                // be used from the controllers.

                if (!mergedOptions.AllowWebApiToBeAuthorizedByACL)
                {
                    ChainOnTokenValidatedEventForClaimsValidation(options.Events, jwtBearerScheme);
                }

                if (subscribeToJwtBearerMiddlewareDiagnosticsEvents)
                {
                    var diagnostics = serviceProvider.GetRequiredService <IJwtBearerMiddlewareDiagnostics>();

                    diagnostics.Subscribe(options.Events);
                }
            });
        }