Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DataProtectionProvider in MVC 5 for dependecy injection correctly

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();
like image 255
Santhos Avatar asked Apr 07 '16 10:04

Santhos


1 Answers

There is a walkthrough that tells you how to register the DataProtectionProvider with Autofac.

builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
like image 139
NightOwl888 Avatar answered Sep 19 '22 16:09

NightOwl888