Exemple #1
0
        // This method works specifically for single tenant application.
        private static void RegisterAuthenticationServices(
            IServiceCollection services,
            IConfiguration configuration)
        {
            AuthenticationServiceCollectionExtensions.ValidateAuthenticationConfigurationSettings(configuration);

            services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
            .AddJwtBearer(options =>
            {
                var azureADOptions = new AzureADOptions();
                configuration.Bind("AzureAd", azureADOptions);
                options.Authority = $"{azureADOptions.Instance}{azureADOptions.TenantId}/v2.0";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudiences    = AuthenticationServiceCollectionExtensions.GetValidAudiences(configuration),
                    ValidIssuers      = AuthenticationServiceCollectionExtensions.GetValidIssuers(configuration),
                    AudienceValidator = AuthenticationServiceCollectionExtensions.AudienceValidator,
                };
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async context =>
                    {
                        var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService <TokenAcquisitionHelper>();
                        context.Success();

                        // Adds the token to the cache, and also handles the incremental consent and claim challenges
                        var jwtToken = AuthenticationHeaderValue.Parse(context.Request.Headers["Authorization"].ToString()).Parameter;
                        await tokenAcquisition.AddTokenToCacheFromJwtAsync(configuration[AuthenticationServiceCollectionExtensions.GraphScopeConfigurationSettingsKey], jwtToken);
                        await Task.FromResult(0);
                    },
                };
            });
        }
Exemple #2
0
        private static IEnumerable <string> GetValidIssuers(IConfiguration configuration)
        {
            var tenantId = configuration[AuthenticationServiceCollectionExtensions.TenantIdConfigurationSettingsKey];

            var validIssuers =
                AuthenticationServiceCollectionExtensions.GetSettings(
                    configuration,
                    AuthenticationServiceCollectionExtensions.ValidIssuersConfigurationSettingsKey);

            validIssuers = validIssuers.Select(validIssuer => validIssuer.Replace("TENANT_ID", tenantId, StringComparison.OrdinalIgnoreCase));

            return(validIssuers);
        }