asp.net-mvcasp.net-coreauthenticationcookies

How to generate COMMON KEY RING to Share cookies across subdomains?


I want to share authentication cookies between main and subdomain in ASP.NET core (.NET 8).

After reading this article about Share authentication cookies with ASP.NET Core Identity, I'm confused about "COMMON KEY RING" and want to know how to generate it.


Solution

  • You could generate a keyfile in an console app like following: package Microsoft.AspNetCore.DataProtection.Extensions

    var dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"E:\test2"), options =>
    {
        options.SetApplicationName("SharedCookieApp");
    });
    var protector = dataProtectionProvider.CreateProtector("myShareing");
    
    //excute a protect, then the key file will generate
    var a=protector.Protect("abc");
    

    Then in the 2 applications which you want to share cookie, you need to disable auto generate new key. Or everytime the keyfile will be overritten.

    builder.Services.AddDataProtection()
        .PersistKeysToFileSystem(new DirectoryInfo(@"E:\test2"))
        .DisableAutomaticKeyGeneration()               //important
        .SetApplicationName("SharedCookieApp");
    

    You could also make a logic to generate key file when file doesn't exist in the application.