aspnet / Security

[Archived] Middleware for security and authorization of web apps. Project moved to https://github.com/aspnet/AspNetCore

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Setting up DataProtectionProvider for cookie authentication

kevinlo opened this issue · comments

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

  1. 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?

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.

@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.