我有一个当前使用Forms身份验证的现有ASP.NET WebForms应用程序。我们正在ASP.NET Core 2中构建一个新站点,它是IIS中的虚拟目录。我们需要在两个站点之间共享身份验证,以便用户不必登录两次。
我已将.NET Core应用程序配置为使用cookie身份验证,如下所示:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "cred";
options.LoginPath = new PathString("/Login");
options.LogoutPath = new PathString("/Logout");
});
登录时,使用此代码创建cookie,并且用户已成功登录:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim("FullName", $"{user.FirstName} {user.LastName}"),
new Claim(ClaimTypes.Role, user.UserType),
new Claim(ClaimTypes.Email, user.EmailAddress),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
return new ClaimsPrincipal(claimsIdentity);
var _authenticationProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(60),
AllowRefresh = true
};
await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, _authenticationProperties);
在我的WebForms应用程序中,我在web.config上将Authentication设置为None,并将其配置为使用Microsoft.Owin.Security.Cookies和Interop,如下所示:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieName = "cred",
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
LoginPath = new PathString("/LoginPage.aspx"),
CookieManager = new SystemWebCookieManager(), //Owin and ASP.NET do not play nicely with Response Cookies. Remove at your peril,
ExpireTimeSpan = TimeSpan.FromHours(1),
TicketDataFormat = new AspNetTicketDataFormat(
new DataProtectorShim(
DataProtectionProvider.Create(new DirectoryInfo(@"d:\keys\"), (builder) => { builder.SetApplicationName("Aliss");})
.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2"))),
});