private static X509Certificate2 GetCertificate(IWebHostEnvironment environment, IConfiguration configuration)
        {
            X509Certificate2 cert;
            var useLocalCertStore     = Convert.ToBoolean(configuration["UseLocalCertStore"]);
            var certificateThumbprint = configuration["CertificateThumbprint"];

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

            return(cert);
        }
    public static async Task <(X509Certificate2 ActiveCertificate, X509Certificate2 SecondaryCertificate)> GetCertificates(CertificateConfiguration certificateConfiguration)
    {
        (X509Certificate2 ActiveCertificate, X509Certificate2 SecondaryCertificate)certs = (null, null);

        if (certificateConfiguration.UseLocalCertStore)
        {
            using X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            var storeCerts = store.Certificates.Find(X509FindType.FindByThumbprint, certificateConfiguration.CertificateThumbprint, false);
            certs.ActiveCertificate = storeCerts[0];
            store.Close();
        }
        else
        {
            if (!string.IsNullOrEmpty(certificateConfiguration.KeyVaultEndpoint))
            {
                var credential = new DefaultAzureCredential();
                var keyVaultCertificateService = new KeyVaultCertificateService(
                    certificateConfiguration.KeyVaultEndpoint,
                    certificateConfiguration.CertificateNameKeyVault);

                var secretClient = new SecretClient(
                    vaultUri: new Uri(certificateConfiguration.KeyVaultEndpoint),
                    credential);

                var certificateClient = new CertificateClient(
                    vaultUri: new Uri(certificateConfiguration.KeyVaultEndpoint),
                    credential);

                certs = await keyVaultCertificateService.GetCertificatesFromKeyVault(secretClient, certificateClient).ConfigureAwait(false);
            }
        }

        // search for local PFX with password, usually local dev
        if (certs.ActiveCertificate == null)
        {
            certs.ActiveCertificate = new X509Certificate2(
                certificateConfiguration.DevelopmentCertificatePfx,
                certificateConfiguration.DevelopmentCertificatePassword);
        }

        return(certs);
    }
        private X509Certificate2 LoadSigningCertificate()
        {
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["KeyVault:AzureADCertThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsStaging() || _environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    Log.Information("Loading signing certificate from local certification store");
                    using (var 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
                {
                    Log.Information("Loading signing certificate from key vault");
                    var vaultConfigSection = Configuration.GetSection("KeyVault");
                    Log.Information($"Key vault configurations. KeyVaultName: {vaultConfigSection["KeyVaultName"]}; "
                                    + $"CertificateName: {vaultConfigSection["CertificateName"]}");
                    var keyVaultService = new KeyVaultCertificateService($"https://{vaultConfigSection["KeyVaultName"]}.vault.azure.net/",
                                                                         vaultConfigSection["AzureADApplicationId"],
                                                                         vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                Log.Information("Loading signing certificate from file");
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "keyvault-myCompany-ch-20191219.pfx"), "");
            }

            return(cert);
        }
Beispiel #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connection            = Configuration.GetConnectionString("DefaultConnection");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_env.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(_env.ContentRootPath, "damienbodserver.pfx"), "");
            }

            // Important The folderForKeyStore needs to be backed up.
            // services.AddDataProtection()
            //    .SetApplicationName("ResourceServer")
            //    .PersistKeysToFileSystem(new DirectoryInfo(folderForKeyStore))
            //    .ProtectKeysWithCertificate(cert);

            services.AddDataProtection()
            .SetApplicationName("ResourceServer")
            .ProtectKeysWithCertificate(cert)
            .AddKeyManagementOptions(options =>
                                     options.XmlRepository = new SqlXmlRepository(
                                         new DataProtectionDbContext(
                                             new DbContextOptionsBuilder <DataProtectionDbContext>().UseSqlite(connection).Options
                                             )
                                         )
                                     );

            services.AddDbContext <DataEventRecordContext>(options =>
                                                           options.UseSqlite(connection)
                                                           );

            services.AddCors();

            var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();

            policy.Headers.Add("*");
            policy.Methods.Add("*");
            policy.Origins.Add("*");
            policy.SupportsCredentials = true;

            services.AddCors(x => x.AddPolicy("corsGlobalPolicy", policy));

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44318/";
                options.ApiName   = "dataEventRecords";
                options.ApiSecret = "dataEventRecordsSecret";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(guestPolicy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            services.AddScoped <IDataEventRecordRepository, DataEventRecordRepository>();
        }
        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>();
        }
Beispiel #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            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("AllowAllHeaders",
                                  builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .WithExposedHeaders("X-Pagination");
                });
            });


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

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

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

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

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

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority       = Config.HOST_URL + "/";
                options.ApiName         = "dataEventRecords";
                options.ApiSecret       = "dataEventRecordsSecret";
                options.SupportedTokens = SupportedTokens.Both;
            });

            //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddTransient <IEmailSender, EmailSender>();

            //IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
            //{
            //    Authority = Config.HOST_URL + "/",
            //    AllowedScopes = new List<string> { "dataEventRecords" },
            //    ApiSecret = "dataEventRecordsSecret",
            //    ApiName = "dataEventRecords",
            //    AutomaticAuthenticate = true,
            //    SupportedTokens = SupportedTokens.Both,
            //    // TokenRetriever = _tokenRetriever,
            //    // required if you want to return a 403 and not a 401 for forbidden responses
            //    AutomaticChallenge = true,
            //};

            //app.UseIdentityServerAuthentication(identityServerValidationOptions);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("admin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Beispiel #8
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connection            = Configuration.GetConnectionString("DefaultConnection");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_webHostEnvironment.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(_webHostEnvironment.ContentRootPath, "damienbodserver.pfx"), "");
            }

            // Important The folderForKeyStore needs to be backed up.
            // services.AddDataProtection()
            //    .SetApplicationName("ResourceServer")
            //    .PersistKeysToFileSystem(new DirectoryInfo(folderForKeyStore))
            //    .ProtectKeysWithCertificate(cert);

            services.AddDataProtection()
            .SetApplicationName("ResourceServer")
            .ProtectKeysWithCertificate(cert)
            .AddKeyManagementOptions(options =>
                                     options.XmlRepository = new SqlXmlRepository(
                                         new DataProtectionDbContext(
                                             new DbContextOptionsBuilder <DataProtectionDbContext>().UseSqlite(connection).Options
                                             )
                                         )
                                     );

            services.AddDbContext <DataEventRecordContext>(options =>
                                                           options.UseSqlite(connection)
                                                           );

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

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:44318/";
                options.ApiName   = "dataEventRecords";
                options.ApiSecret = "dataEventRecordsSecret";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });

            services.AddControllers()
            .AddNewtonsoftJson()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddScoped <IDataEventRecordRepository, DataEventRecordRepository>();
        }
        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
            });
        }
Beispiel #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, "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>();
        }
        /// <summary>
        /// Add custom signing certificate from certification store according thumbprint or from file
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configuration"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddCustomSigningCredential(this IIdentityServerBuilder builder, IConfiguration configuration, ILogger logger)
        {
            var certificateConfiguration = configuration.GetSection(nameof(CertificateConfiguration)).Get <CertificateConfiguration>();

            if (certificateConfiguration.UseSigningCertificateThumbprint)
            {
                if (string.IsNullOrWhiteSpace(certificateConfiguration.SigningCertificateThumbprint))
                {
                    throw new Exception(SigningCertificateThumbprintNotFound);
                }

                var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                certStore.Open(OpenFlags.ReadOnly);

                var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certificateConfiguration.SigningCertificateThumbprint, true);
                if (certCollection.Count == 0)
                {
                    throw new Exception(CertificateNotFound);
                }

                var certificate = certCollection[0];

                builder.AddSigningCredential(certificate);
            }
            else if (certificateConfiguration.UseSigningCertificatePfxFile)
            {
                if (string.IsNullOrWhiteSpace(certificateConfiguration.SigningCertificatePfxFilePath))
                {
                    throw new Exception(SigningCertificatePathIsNotSpecified);
                }

                if (File.Exists(certificateConfiguration.SigningCertificatePfxFilePath))
                {
                    logger.LogInformation("inside signing certificate ");
                    try
                    {
                        builder.AddSigningCredential(new X509Certificate2(certificateConfiguration.SigningCertificatePfxFilePath, certificateConfiguration.SigningCertificatePfxFilePassword));
                        logger.LogInformation("AddSigningCredential ");
                    }
                    catch (CryptographicException e)
                    {
                        logger.LogError($"There was an error adding the key file - during the creation of the signing key {e.Message}");
                    }
                }
                else
                {
                    throw new Exception($"Signing key file: {certificateConfiguration.SigningCertificatePfxFilePath} not found");
                }
            }
            else if (certificateConfiguration.AzureKeyVault)
            {
                // Azure deployment, will be used if deployed to Azure
                var keyVaultService = new KeyVaultCertificateService(certificateConfiguration.AzureKeyVaultEndPoint, certificateConfiguration.AzureKeyVaultClientId, certificateConfiguration.AzureKeyVaultClientSecret, logger);
                builder.AddSigningCredential(keyVaultService.GetCertificateFromKeyVault(certificateConfiguration.AzureKeyVaultCertificateName));
            }
            else if (certificateConfiguration.UseTemporarySigningKeyForDevelopment)
            {
                builder.AddDeveloperSigningCredential();
            }

            return(builder);
        }
Beispiel #12
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>();
        }
Beispiel #13
0
        public void ConfigureServices(IServiceCollection services)
        {
            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 <EmailSettings>(Configuration.GetSection("EmailSettings"));

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

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

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

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

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority       = Config.HOST_URL + "/";
                options.ApiName         = "dataEventRecords";
                options.ApiSecret       = "dataEventRecordsSecret";
                options.SupportedTokens = SupportedTokens.Both;
            });

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("admin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });

            services.AddControllers()
            .AddNewtonsoftJson()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllersWithViews()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddViewLocalization();
        }
Beispiel #14
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>();
        }
Beispiel #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});


            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.Configure <GeneralConfig>(Configuration.GetSection("GeneralConfig"));

            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.Configure <SmtpEmailSettings>(Configuration.GetSection("SmtpEmailSettings"));
            services.AddSingleton <SmtpClient>((serviceProvider) =>
            {
                var config = serviceProvider.GetRequiredService <IConfiguration>();
                return(new SmtpClient()
                {
                    Host = config.GetValue <String>("SmtpEmailSettings:Host"),
                    Port = config.GetValue <int>("SmtpEmailSettings:Port"),
                    Credentials = new NetworkCredential(
                        config.GetValue <String>("SmtpEmailSettings:Username"),
                        config.GetValue <String>("SmtpEmailSettings:Password")
                        ),
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network
                });
            });

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

            string connectionString   = Configuration.GetConnectionString("DefaultConnection");
            var    migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(connectionString));

            services.AddIdentity <ApplicationUser, IdentityRole>(
                config =>
            {
                config.SignIn.RequireConfirmedEmail    = true;
                config.Password.RequireDigit           = false;
                config.Password.RequiredLength         = 7;
                config.Password.RequireLowercase       = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

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

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddSigningCredential(cert)
            .AddAspNetIdentity <ApplicationUser>()
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(connectionString,
                                                            sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(connectionString,
                                                            sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                // options.TokenCleanupInterval = 15; // frequency in seconds to cleanup stale grants. 15 is useful during debugging
            })
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            //  .AddIdentityServerAuthentication(options =>
            //  {
            //      options.Authority = Config.HOST_URL + "/";
            //      options.ApiName = "dataEventRecords";
            //      options.ApiSecret = "dataEventRecordsSecret";
            //      options.SupportedTokens = SupportedTokens.Both;
            //  });

            //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddTransient <IEmailSender, EmailSender>();

            //IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
            //{
            //    Authority = Config.HOST_URL + "/",
            //    AllowedScopes = new List<string> { "dataEventRecords" },
            //    ApiSecret = "dataEventRecordsSecret",
            //    ApiName = "dataEventRecords",
            //    AutomaticAuthenticate = true,
            //    SupportedTokens = SupportedTokens.Both,
            //    // TokenRetriever = _tokenRetriever,
            //    // required if you want to return a 403 and not a 401 for forbidden responses
            //    AutomaticChallenge = true,
            //};

            //app.UseIdentityServerAuthentication(identityServerValidationOptions);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("admin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });


            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com";
                options.ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh";
            });
            //.AddOpenIdConnect("oidc", "OpenID Connect", options =>
            //{
            //    options.Authority = "https://demo.identityserver.io/";
            //    options.ClientId = "implicit";
            //    options.SaveTokens = true;

            //    options.TokenValidationParameters = new TokenValidationParameters
            //    {
            //        NameClaimType = "name",
            //        RoleClaimType = "role"
            //    };
            //}).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.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("ar"),
                    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.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));
                };
            });
        }