示例#1
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            var x509Certificate2Certs = GetCertificates(_environment, _configuration);

            //var x509Certificate2Certs = GetCertificatesDirect(_environment);
            AddLocalizationConfigurations(services);

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2");

            var clientId     = _configuration["MicrosoftClientId"];
            var clientSecret = _configuration["MircosoftClientSecret"];

            services.AddAuthentication()
            .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options =>      // Microsoft common
            {
                //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                options.ClientId     = clientId;
                options.ClientSecret = clientSecret;
                options.SignInScheme = "Identity.External";
                options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                options.ResponseType = "code";
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    NameClaimType  = "email",
                };
                options.CallbackPath = "/signin-microsoft";
                options.Prompt       = "login"; // login, consent
            });

            services.AddControllersWithViews(options =>
            {
                options.Filters.Add(new SecurityHeadersAttribute());
            })
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            })
            .AddNewtonsoftJson();

            //var stsConfig = _configuration.GetSection("StsConfig");
            var apiSecret          = _configuration["ApiSecret"];
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            var identityServer = services.AddIdentityServer()
                                 //.AddDeveloperSigningCredential()
                                 .AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
                                 .AddInMemoryIdentityResources(Config.GetIdentityResources())
                                 .AddInMemoryApiResources(Config.GetApis(apiSecret))
                                 .AddInMemoryClients(Config.GetClients())
                                 .AddAspNetIdentity <ApplicationUser>()
                                 .AddProfileService <IdentityWithAdditionalClaimsProfileService>()
                                 .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"),
                                                                  sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;     // interval in seconds
            });

            if (x509Certificate2Certs.SecondaryCertificate != null)
            {
                identityServer.AddValidationKey(x509Certificate2Certs.SecondaryCertificate);
            }

            services.Configure <Fido2Configuration>(_configuration.GetSection("fido2"));
            services.Configure <Fido2MdsConfiguration>(_configuration.GetSection("fido2mds"));
            services.AddScoped <Fido2Storage>();
            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout         = TimeSpan.FromMinutes(2);
                options.Cookie.HttpOnly     = true;
                options.Cookie.SameSite     = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            });
        }