简体   繁体   中英

sharing asp.net 4 forms authentication cookie with asp.net core 2.0

We have multiple applications setup in IIS with one application handling the login for all applications. This application is an asp.net 4 site and uses a forms authentication cookie.

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

We can successfully use this cookie to login to asp.net 4.5 apps using owin.

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());
    }
}

In asp.net core 2.0 I do not know to to wire up the app to use the shared cookie

In Startup.cs Configure

app.UseAuthentication();

ConfigureServices

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

My understanding is that you need to change from relying on machine key for your cookie encryption and switch over to use a DataProtectionProvider. This article in the docs spells out everything very clearly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM