예제 #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            _clientId     = _configuration["MicrosoftClientId"];
            _clientSecret = _configuration["MircosoftClientSecret"];
            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)
                                        .GetAwaiter().GetResult();

            AddLocalizationConfigurations(services);

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

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

            services.AddAuthentication()
            //.AddMicrosoftAccount(options =>
            //{
            //    options.ClientId = _clientId;
            //    options.SignInScheme = "Identity.External";
            //    options.ClientSecret = _clientSecret;
            //})
            .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.UsePkce      = true;
                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();

            //RsaSecurityKey rsaSecurityKey =
            //    new RsaSecurityKey(x509Certificate2Certs.ActiveCertificate.GetRSAPrivateKey());

            ECDsaSecurityKey eCDsaSecurityKey
                = new ECDsaSecurityKey(x509Certificate2Certs.ActiveCertificate.GetECDsaPrivateKey());

            services.AddIdentityServer()
            //.AddSigningCredential(x509Certificate2)
            .AddSigningCredential(eCDsaSecurityKey, "ES384")     // ecdsaCertificate
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.Configure <Fido2Configuration>(_configuration.GetSection("fido2"));
            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;
            });
        }
예제 #2
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)
                                        .GetAwaiter().GetResult();

            AddLocalizationConfigurations(services);

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

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

            services.AddAuthentication()
            .AddOpenIdConnect("aad", "Login with Azure AD", options =>      // Microsoft common
            {
                //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                options.ClientId     = "your_client_id";  // ADD APP Registration ID
                options.ClientSecret = "your_secret";     // ADD APP Registration secret
                options.SignInScheme = "Identity.External";
                options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                options.ResponseType = "code";
                options.UsePkce      = false; // live does not support this yet
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // ALWAYS VALIDATE THE ISSUER IF POSSIBLE !!!!
                    ValidateIssuer = false,
                    // ValidIssuers = new List<string> { "tenant..." },
                    NameClaimType = "email",
                };
                options.CallbackPath = "/signin-microsoft";
                options.Prompt       = "login"; // login, consent
            });

            services.AddAntiforgery(options =>
            {
                options.SuppressXFrameOptionsHeader = true;
                options.Cookie.SameSite             = SameSiteMode.Strict;
                options.Cookie.SecurePolicy         = CookieSecurePolicy.Always;
            });

            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 identityServer = services.AddIdentityServer()
                                 .AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
                                 .AddInMemoryIdentityResources(Config.GetIdentityResources())
                                 .AddInMemoryApiResources(Config.GetApiResources())
                                 .AddInMemoryApiScopes(Config.GetApiScopes())
                                 .AddInMemoryClients(Config.GetClients(stsConfig))
                                 .AddAspNetIdentity <ApplicationUser>()
                                 .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

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

            services.Configure <Fido2Configuration>(_configuration.GetSection("fido2"));
            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;
            });
        }
예제 #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig     = Configuration.GetSection("StsConfig");
            var _clientId     = Configuration["MicrosoftClientId"];
            var _clientSecret = Configuration["MircosoftClientSecret"];

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddSingleton <IAuthorizationHandler, IsAdminHandler>();

            var x509Certificate2Certs = GetCertificates(_environment, Configuration)
                                        .GetAwaiter().GetResult();

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

            AddLocalizationConfigurations(services);

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder
                    .AllowCredentials()
                    .WithOrigins("https://localhost:44311", "https://localhost:44390", "https://localhost:44395", "https://localhost:44318")
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

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


            services.AddScoped <IUserClaimsPrincipalFactory <ApplicationUser>,
                                AdditionalUserClaimsPrincipalFactory>();

            services.AddAuthentication()
            .AddOpenIdConnect("aad", "Login with Azure AD", options =>
            {
                options.Authority = $"https://login.microsoftonline.com/common";
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = false
                };
                options.ClientId     = "99eb0b9d-ca40-476e-b5ac-6f4c32bfb530";
                options.CallbackPath = "/signin-oidc";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("IsAdmin", policyIsAdminRequirement =>
                {
                    policyIsAdminRequirement.Requirements.Add(new IsAdminRequirement());
                });
            });
            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();

            services.AddIdentityServer()
            .AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            // .leg
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            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;
            });
        }
예제 #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig = _configuration.GetSection("StsConfig");

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

            _clientId     = _configuration["MicrosoftClientId"];
            _clientSecret = _configuration["MircosoftClientSecret"];
            var authConfigurations    = _configuration.GetSection("AuthConfigurations");
            var useLocalCertStore     = Convert.ToBoolean(_configuration["UseLocalCertStore"]);
            var certificateThumbprint = _configuration["CertificateThumbprint"];

            var x509Certificate2Certs = GetCertificates(_environment, _configuration)
                                        .GetAwaiter().GetResult();

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


            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();
            AddLocalizationConfigurations(services);
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2");

            if (_clientId != null)
            {
                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.UsePkce      = false; // live does not support this yet
                    options.Scope.Add("profile");
                    options.Scope.Add("email");
                    options.ClaimActions.MapUniqueJsonKey("preferred_username", "preferred_username");
                    options.ClaimActions.MapAll();  // ClaimActions.MapUniqueJsonKey("amr", "amr");
                    //options.ClaimActions.Remove("amr");
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.TokenValidationParameters     = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        NameClaimType  = "email",
                    };
                    options.CallbackPath = "/signin-microsoft";
                    options.Prompt       = "login"; // login, consent
                    options.Events       = new OpenIdConnectEvents
                    {
                        OnRedirectToIdentityProvider = context =>
                        {
                            context.ProtocolMessage.SetParameter("acr_values", "mfa");

                            return(Task.FromResult(0));
                        }
                    };
                });
            }
            else
            {
                services.AddAuthentication();
            }

            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();

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            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;
            });
        }