aspnet / Security

[Archived] Middleware for security and authorization of web apps. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
1.27k stars 600 forks source link

Setting up DataProtectionProvider for cookie authentication #1868

Closed kevinlo closed 5 years ago

kevinlo commented 5 years ago

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:

1) 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",
                };
            };

2) 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?

Tratcher commented 5 years ago

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.

kevinlo commented 5 years ago

@Tratcher Ok. I don't know the history and I am wondering why the options one is there and the use case of it. If it is old pattern for backward compatibility, I won't use it. Thanks.