public static void AddConfiguredDataProtection(this IServiceCollection services, IConfiguration configuration) { DataProtectionOptions dataProtectionOptions = configuration.GetValue <DataProtectionOptions>("DataProtection"); if (dataProtectionOptions == null) { // Automatic - let ASP.NET Core defaults in place return; } IDataProtectionBuilder dataProtectionBuilder; switch (dataProtectionOptions.StorageOptions?.Type ?? DataProtectionStorageType.InMemory) { case DataProtectionStorageType.InMemory: dataProtectionBuilder = ConfigureForInMemory(services); break; case DataProtectionStorageType.File: dataProtectionBuilder = ConfigureForFile(services, dataProtectionOptions); break; default: throw new ArgumentOutOfRangeException(); } switch (dataProtectionOptions.Protection) { case DataProtectionProtectionType.None: break; case DataProtectionProtectionType.Certificate: ConfigureForCertificate(dataProtectionBuilder, dataProtectionOptions); break; case DataProtectionProtectionType.Windows: ConfigureWindowProtection(dataProtectionBuilder); break; default: throw new ArgumentOutOfRangeException(); } if (dataProtectionOptions.Lifetime != null) { dataProtectionBuilder.SetDefaultKeyLifetime(dataProtectionOptions.Lifetime.Value); } }
private static void ConfigureForCertificate(IDataProtectionBuilder builder, DataProtectionOptions dataProtectionOptions) { CertificateDataProtectionOptions certificateOptions = dataProtectionOptions.Certificate; if (certificateOptions == null) { throw new InvalidOperationException($"{nameof(DataProtectionOptions)}:{nameof(dataProtectionOptions.Certificate)} not set"); } certificateOptions.Validate(); var certificate = new X509Certificate2(certificateOptions.CertificatePath, certificateOptions.Password); builder.ProtectKeysWithCertificate( certificate ); }
private static IDataProtectionBuilder ConfigureForFile(IServiceCollection services, DataProtectionOptions dataProtectionOptions) { IDataProtectionBuilder builder = services.AddConfiguredDataProtection(); DataProtectionStorageOptions storageOptions = dataProtectionOptions.File; if (storageOptions == null) { throw new InvalidOperationException($"{nameof(DataProtectionOptions)}:{nameof(dataProtectionOptions.File)} not set"); } if (storageOptions.Path == "auto") { storageOptions.Path = EnvironmentPath.CreatePath("key-store"); } var directory = new DirectoryInfo(storageOptions.Path); directory.Create(); builder.PersistKeysToFileSystem( directory ); return(builder); }