Shared cookie authentication between ASP.NET Core

2019-02-05 08:37发布

We have two .NET-apps running shared cookie authentication. One is an ASP.NET Core RC1 app, and the other is a classic .NET 4.5.1 app.

This is currently set up using the outdated Microsoft.Owin.Security.Cookies.Interop in the Configuration method of Startup.cs:

This works fine, but is no supported method for RC2.

How can we get going with shared cookie authentication for RC2?

1条回答
你好瞎i
2楼-- · 2019-02-05 09:01

Combining https://github.com/GrabYourPitchforks/aspnet5-samples/tree/dev/CookieSharing and Sharing authentication cookie among Asp.Net Core 1 (MVC6) and MVC 5 applications I was able to come up with a working solution. I have no idea if this is the "correct" way to to it, but it works, so here it goes:

  1. Use the nuget-package Microsoft.Owin.Security.Interop 1.0.0-rc2-final in both of the applications.

  2. Create a TicketDataFormat using DataProtectionProvider specifying the same location on disk for the encryption keys, as well as the same purpose.

  3. Configure cookie authentication the owin way in both of the applications. Specify the same CookieName and TicketDataFormat:

.NET 4.5.1, in the Configure method of Startup.cs:

var authenticationType = "Cookies";
var cookieName = "myCookieName";
var cookieEncryptionKeyPath= "C:/mypath";

var dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(cookieEncryptionKeyPath));
var dataProtector = dataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", authenticationType, "v2");
var ticketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));

app.SetDefaultSignInAsAuthenticationType(authenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = authenticationType,
            CookieName = cookieName,
            TicketDataFormat = ticketDataFormat
        });

.NET CORE RC2 in the Configure method of Startup.cs:

var authenticationType = "Cookies";
var cookieName = "myCookieName";
var cookieEncryptionKeyPath= "C:/mypath";

var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(cookieEncryptionKeyPath));
var dataProtector = protectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", authenticationType, "v2");
var ticketFormat = new TicketDataFormat(dataProtector);


app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    CookieName = options.CookieName,
                    CookieDomain = options.CookieDomain,
                    TicketDataFormat = ticketFormat
                });
查看更多
登录 后发表回答