我们有两个运行共享 cookie 身份验证的 .NET 应用程序。一个是 ASP.NET Core RC1 应用,另一个是经典的 .NET 4.5.1 应用。
这是目前在 Startup.cs
的 Configuration
方法中使用过时的 Microsoft.Owin.Security.Cookies.Interop
设置的:
这工作正常,但不是 RC2 支持的方法。
我们如何开始使用 RC2 的共享 cookie 身份验证?
最佳答案
合并https://github.com/GrabYourPitchforks/aspnet5-samples/tree/dev/CookieSharing和 Sharing authentication cookie among Asp.Net Core 1 (MVC6) and MVC 5 applications我能够想出一个可行的解决方案。我不知道这是否是“正确”的方法,但它有效,所以它是这样的:
在两个应用程序中使用 nuget-package
Microsoft.Owin.Security.Interop 1.0.0-rc2-final
。使用
DataProtectionProvider
创建一个TicketDataFormat
,为加密 key 在磁盘上指定相同的位置,目的相同。在两个应用程序中以 owin 方式配置 cookie 身份验证。指定相同的
CookieName
和TicketDataFormat
:
.NET 4.5.1,在Startup.cs
的Configure方法中:
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
});
Startup.cs
的Configure方法中的.NET CORE RC2:
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
});
关于c# - ASP.NET Core RC2 和 .NET 4.5.1 应用程序之间的共享 cookie 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37529741/