diff --git a/src/BCards.Web/BCards.Web.csproj b/src/BCards.Web/BCards.Web.csproj index d2c8ef8..802d00d 100644 --- a/src/BCards.Web/BCards.Web.csproj +++ b/src/BCards.Web/BCards.Web.csproj @@ -19,20 +19,21 @@ - - - - - - - - - - - + + + + + + + + + + + + - \ No newline at end of file + diff --git a/src/BCards.Web/Program.cs b/src/BCards.Web/Program.cs index fdcb9c5..a5f0b4d 100644 --- a/src/BCards.Web/Program.cs +++ b/src/BCards.Web/Program.cs @@ -2,6 +2,7 @@ using BCards.Web.Configuration; using BCards.Web.Services; using BCards.Web.Repositories; using BCards.Web.HealthChecks; +using AspNetCore.DataProtection.MongoDb; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.Localization; @@ -19,6 +20,7 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Serilog.Sinks.OpenSearch; using BCards.Web.TestSupport; using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.DataProtection; var builder = WebApplication.CreateBuilder(args); @@ -233,6 +235,30 @@ builder.Services.AddScoped(serviceProvider => return client.GetDatabase(settings.DatabaseName); }); +var dataProtectionSection = builder.Configuration.GetSection("DataProtection:Mongo"); +var dataProtectionConnectionString = dataProtectionSection.GetValue("ConnectionString") + ?? builder.Configuration.GetSection("MongoDb").GetValue("ConnectionString"); +var dataProtectionDatabase = dataProtectionSection.GetValue("DatabaseName") + ?? builder.Configuration.GetSection("MongoDb").GetValue("DatabaseName") + ?? "BCardsDB"; +var dataProtectionCollection = dataProtectionSection.GetValue("CollectionName") ?? "DataProtectionKeys"; + +if (!string.IsNullOrWhiteSpace(dataProtectionConnectionString)) +{ + Log.Information("Configuring DataProtection to persist keys in MongoDB database {Database} / collection {Collection}", + dataProtectionDatabase, dataProtectionCollection); + + builder.Services.AddDataProtection() + .SetApplicationName("BCards") + .PersistKeysToMongoDb( + () => new MongoClient(dataProtectionConnectionString).GetDatabase(dataProtectionDatabase), + dataProtectionCollection); +} +else +{ + Log.Warning("DataProtection MongoDB configuration missing; encryption keys will be ephemeral per container."); +} + // Stripe Configuration with validation builder.Services.Configure( builder.Configuration.GetSection("Stripe")); @@ -787,4 +813,4 @@ finally Log.CloseAndFlush(); } -public partial class Program { } \ No newline at end of file +public partial class Program { }