How to persist .NET Data Protection keys
There are a number of ways to persist .NET Data Protection keys, this article explains how to persist the keys to disk on our GreenStack platform.
If you with to persist to a SQL Database or Azure Blob storage please take a look at the documentation found here.
We have made persisting to disk super simple, simply add the below DataProtectionComposer.cs to your project:
Umbraco V13
Section titled “Umbraco V13”using Microsoft.AspNetCore.DataProtection;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Umbraco.Cms.Core.Composing;using Umbraco.Cms.Core.DependencyInjection;
namespace Abbeyfield.Core.Composers;
public class DataProtectionComposer : IComposer{ public void Compose(IUmbracoBuilder builder) { var environment = builder.Services.BuildServiceProvider() .GetRequiredService<IHostEnvironment>();
var keysPath = environment.IsProduction() ? "/app/keys" : Path.Combine(environment.ContentRootPath, "DataProtection-Keys");
if (!Directory.Exists(keysPath)) { Directory.CreateDirectory(keysPath); }
builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(keysPath)); }}Umbraco V17
Section titled “Umbraco V17”using Microsoft.AspNetCore.DataProtection;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Umbraco.Cms.Core.Composing;using Umbraco.Cms.Core.DependencyInjection;
namespace UmbPanel.Core.Composers;
public class DataProtectionComposer : IComposer{ public void Compose(IUmbracoBuilder builder) { var environment = builder.Services.BuildServiceProvider() .GetRequiredService<IHostEnvironment>();
if (environment.IsProduction()) { var keysPath = Path.Combine("/app/keys");
if (!Directory.Exists(keysPath)) { Directory.CreateDirectory(keysPath); }
builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(keysPath)); } }}This will ensure the composer is only run in the Production environment, allowing your local to run as normal, if you have named your environment something different that Production please ensure to update the code accordingly.