private static void AddLocalizationConfigurations(IServiceCollection services)
        {
            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("gsw-CH"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("zh-Hans")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });
        }
Exemple #2
0
        private static void AddLocalizationConfigurations(IServiceCollection services, string sharedResourceAssemblyName)
        {
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddSingleton(sp => {
                var factory = sp.GetRequiredService <IStringLocalizerFactory>();
                return(factory.Create("SharedResource", sharedResourceAssemblyName));
            });

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("gsw-CH"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("zh-Hans")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QueryParameterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig = Configuration.GetSection("StsConfig");

            _clientId     = Configuration["MicrosoftClientId"];
            _clientSecret = Configuration["MircosoftClientSecret"];
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");
            }

            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.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

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

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

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddSingleton <IAuthorizationHandler, IsAdminHandler>();

            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.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-CH", uiCulture: "de-CH");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

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

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            _clientId     = Configuration["MicrosoftClientId"];
            _clientSecret = Configuration["MircosoftClientSecret"];
            var authConfigurations    = Configuration.GetSection("AuthConfigurations");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "sts_dev_cert.pfx"), "1234");
            }

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

            services.Configure <AuthConfigurations>(Configuration.GetSection("AuthConfigurations"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            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.Scope.Add("profile");
                    options.Scope.Add("email");
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        NameClaimType  = "email",
                    };
                    options.CallbackPath = "/signin-microsoft";
                    options.Prompt       = "login"; // login, consent
                });
            }
            else
            {
                services.AddAuthentication();
            }

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

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("gsw-CH"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("zh-Hans")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

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

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(authConfigurations))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc()
            .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            services.AddTransient <IEmailSender, EmailSender>();

            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddInMemoryIdentityResources(Config.GetIdentityResources())
                          .AddInMemoryApiResources(Config.GetApiResources())
                          .AddInMemoryClients(Config.GetClients())
                          .AddAspNetIdentity <ApplicationUser>();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }
        }
Exemple #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "sts_dev_cert.pfx"), "1234");
            }

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

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            // TODO: Google Auth Config:
            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "[ClientId]";
                options.ClientSecret = "[ClientSecret]";
            });

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

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("gsw-CH"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("zh-Hans")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

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

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
Exemple #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig = Configuration.GetSection("StsConfig");

            X509Certificate2 cert;

            cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");

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

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("gsw-CH"),
                    new CultureInfo("fr-FR")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "sts_dev_cert.pfx"), "1234");
            }

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

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddTransient <IEndSessionRequestValidator, MyEndSessionRequestValidator>();

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders();

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("gsw-CH"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("zh-Hans")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

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

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .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
            });
        }
Exemple #9
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert = null;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "sts_dev_cert.pfx"), "1234");
            }

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

            services.Configure <StsConfig>(stsConfig);
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
            });

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("zh-Hans")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            //services.AddCors(options => options.AddPolicy("SelfOwner", b =>
            //        b.WithOrigins("http://localhost:4200",
            //                      "https://localhost:4200",
            //                      "http://localhost:5001",
            //                      "https://localhost:44344")
            //         .AllowAnyMethod()
            //         .AllowAnyHeader()));


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

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
Exemple #10
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");
            }

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

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-CH", uiCulture: "de-CH");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                // Cookie is required for the logout, query parameters at not supported with the endsession endpoint
                // Only works in the same domain
                var providerCookie = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                // options.RequestCultureProviders.Insert(0, providerCookie);
                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }