Setting up DataProtectionProvider for cookie authentication
kevinlo opened this issue · comments
kevinlo commented
After some debugging, I finally find out there are two ways to set the DataProtectionProvider to the Cookie Authentication that I can use for sharing the cookie for different app in web farm case:
- AddDataProtection to the Services and it will be injected into PostConfigureCookieAuthenticationOptions e.g.
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(myDataProtectionPath))
.SetApplicationName("MyApp")
.ProtectKeysWithCertificate(myCertificate);
services.AddAuthentication()
.AddCookie(CookieScheme, options =>
{
options.Cookie = new CookieBuilder()
{
HttpOnly = true,
Name = "MyCookie",
};
};
- Setting it at the CookieAuthenticationOptions and the PostConfigureCookieAuthenticationOptions.PostConfig will use it e.g.
services.AddAuthentication()
.AddCookie(CookieScheme, options =>
{
options.Cookie = new CookieBuilder()
{
HttpOnly = true,
Name = "MyCookie",
};
options.DataProtectionProvider = DataProtectionProvider.Create(
new DirectoryInfo(myDataProtectionPath,
builder => { builder.SetApplicationName("MyApp");},
myCertificate
);
};
Which one is the prefer way and what is the use case of them?
Chris Ross commented
Yes setting it up in DI is the recommended approach. Setting it directly on the options is a very old pattern that predates DI support.