AddDataProtection - Register PersistKeysToFileSystem and PersistKeysToDbContext at the same time

92 Views Asked by At

While using the Data Protection API and I register AddDataProtection with both PersistKeysToDbContext and PersistKeysToDbContext. How do I choose which one to use when I call CreateProtector on IDataProtectionProvider in the Controller? I am hoping I do not have to create multiple solutions just for a one line difference!

Here I register Data Protection

builder.Services.AddDataProtection()
    //.PersistKeysToDbContext<DataContext>() //Not sure how to choose between both
    .PersistKeysToFileSystem(new DirectoryInfo(folderPath))
    .SetApplicationName("my-app");

Here, at the moment, I can only use one or the other

    private readonly IDataProtector _dataProtector;

    public FileSystemKeyManagementController(IDataProtectionProvider provider)
    {
        _dataProtector = provider.CreateProtector("my-app");
    }

I am looking for a solution where, for example, FirstController will use PersistKeysToFileSystem and SecondController uses PersistKeysToDbContext. So when I call _dataProtector.Protect("string to secure") depending on controller, the data either ends up on a file system or database table.

Any ideas greatly appreciated.

I tried registering both PersistKeysToDbContext and PersistKeysToFileSystem but the last seems to win.

0

There are 0 best solutions below