与asp.net core 2.0共享asp.net 4表单身份验证cookie

时间:2017-09-08 14:38:08

标签: asp.net cookies forms-authentication asp.net-core-2.0

我们在IIS中设置了多个应用程序,其中一个应用程序处理所有应用程序的登录。此应用程序是一个asp.net 4站点,并使用表单身份验证cookie。

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" protection="All" cookieless="UseCookies" path="/" name="CookieName" />
</authentication>

我们可以使用owin成功使用此cookie登录asp.net 4.5应用程序。

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            TicketDataFormat = new SharedTicketDataFormat(),
            CookieName = "CookieName",
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity =
                    SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });


public class SharedTicketDataFormat : ISecureDataFormat<AuthenticationTicket>
{
    public string Protect(AuthenticationTicket data)
    {
        return FormsAuthentication.Encrypt(new FormsAuthenticationTicket(data.Identity.Name, false, -1));
    }
    public AuthenticationTicket Unprotect(string protectedText)
    {
        var ticket = FormsAuthentication.Decrypt(protectedText);
        var identity = new FormsIdentity(ticket);
        return new AuthenticationTicket(identity, new AuthenticationProperties());
    }
}

在asp.net core 2.0中,我不知道要连接应用程序以使用共享cookie

在Startup.cs中 配置

app.UseAuthentication();

ConfigureServices

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options =>
        {
            options.Cookie.Name = "CookieName";
        });

1 个答案:

答案 0 :(得分:1)

我的理解是,您需要从依靠机器密钥进行cookie加密转变,然后切换为使用DataProtectionProvider。文档中的这篇文章非常清楚地阐明了所有内容:

https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-3.1#share-authentication-cookies-with-aspnet-core-identity