When trying to create a DataProtectionProvider
manually I have stumbled upon the Microsoft documenation to DpapiDataProtectionProvider
which says:
Used to provide the data protection services that are derived from the Data Protection API. It is the best choice of data protection when you application is not hosted by ASP.NET and all processes are running as the same domain identity.
A question suddenly arises: What is the best choice when your application IS hosted by ASP.NET?
Searching further, it seems the best choice is to obtain the DataProtectionProvider
from OWIN. That can be done in Startup configuration, where you have IAppBuilder
and using AppBuilderExtensions
located in Microsoft.Owin.Security.DataProtection
namespace you can call app.GetDataProtectionProvider()
.
So far, I am quite satisfied. However, now you want to inject the DataProtectionProvider
in a constructor of your class (e.g. a UserManager
). I have seen one suggestion where you store the DataProtectionProvider
in a static property and then use it where you need, but that seems like a rather wrong solution.
I think a solution similar to the following piece of code would be appropriate (using ninject container):
kernel.Bind<IDataProtectionProvider>()
// beware, method .GetDataProtectionProvider() is fictional
.ToMethod(c => HttpContext.Current.GetOwinContext().GetDataProtectionProvider())
.InRequestScope();
There is a walkthrough that tells you how to register the DataProtectionProvider with Autofac.
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With