3

My issue is that I would like to share the ASP.NET identity cookie between .NET Core and .NET

I have the latest version of ASP.NET Identity in both places - the .NET Core is a new login page, the .NET is a legacy app that will be converted to .NET Core in the distant future.

I would like the two apps to share the cookie so if you log out of one, it logs out of the other.

Has anyone any experience of this? Know what settings are needed? Surely its something that has come up somewhere before?

This is my code: ASP.NET Core (.NET 6) (login page)

builder.Services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp\common"))
    //.ProtectKeysWithCertificate("thumbprint")
    .SetApplicationName("SharedCookieApp");

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
    options.SlidingExpiration = true;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.Name = ".MyCookie";
});

ASP.NET 4.8 (legacy app)

public void ConfigureAuth(IAppBuilder app)
{
    // Enable the application to use a cookie to store information for the signed in user
    // and to use a cookie to temporarily store information about a user logging in with a third party login provider
    // Configure the sign in cookie
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Identity.Application",
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
        },

        // TODO: Need to make the Dataprotection work on Azure

        CookieName = ".AspNet.SharedCookie",
        CookieSameSite = Microsoft.Owin.SameSiteMode.Lax,
        CookieSecure = CookieSecureOption.Always,
        TicketDataFormat = new AspNetTicketDataFormat(
            new DataProtectorShim(
                DataProtectionProvider.Create(new DirectoryInfo(@"c:\temp\common"),
                builder => builder.SetApplicationName("SharedCookieApp"))//.ProtectKeysWithCertificate("thumbprint") // for production
                .CreateProtector(
                        "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                  // Must match the Scheme name used in the ASP.NET Core app, i.e. IdentityConstants.ApplicationScheme
                  "Identity.Application",
                  "v2"))),
        CookieManager = new Microsoft.Owin.Infrastructure.ChunkingCookieManager()
            });
         );

      app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
      app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

    }

I have created a github repo with what I think is working code. I would very much appreciate any comments as there doesn't appear to be an example on the web that I could find anyway.

https://github.com/philipcj/aspnetidentitysharecoreand4.8

Philip Johnson
  • 1,091
  • 10
  • 24
  • Have you tried something so far? I believe, if the two applications run on the same domain (different subdomains allowed) it should be no problem. – Xerillio May 27 '23 at 17:41
  • They are on the same domain (different subdomains). I have tried naming the cookie to ensure its the same in both cases but was suspecting the cookie format might be different. So far, it isn't working logging out of one doesn't log out of the other. – Philip Johnson May 30 '23 at 09:23
  • I have added my code examples. If you logout from the legacy app, it logs out using the .Core app as it should. Then both are logged out. If I log out from the .Core app, the legacy app isn't aware that I've logged out for a few minutes. – Philip Johnson May 30 '23 at 13:55
  • I have found the cookies are being stored in different subdomains, but they are a different format between the two so making the domain name the name of the login app probably won't help. How to configure so the cookie formats are the same is my question – Philip Johnson May 31 '23 at 08:53
  • 1
    I have faced a similar problem before, and the only way I solved it was to handle login cookies through a sort of SSO middleware. The middleware generates the cookies and handles the state, then passes control back to the requester, which just checks for a valid cookie with an auth token.you then ask the middleware to bin the cookie and deactivate the token when a user requests logout in either location. – Andy Wynn Jun 04 '23 at 07:08
  • 1
    here is an example implementation of a custom authentication provider for SSO using Duende https://medium.com/geekculture/build-your-own-single-sign-on-sso-server-in-asp-net-core-4344f6b390d1 – Emre Bener Jun 05 '23 at 13:31
  • 1
    If it's within the budget, you can also consider Identity Platform (Azure) for external authentication. here is the documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/index-web-app It's a vast topic and your question is not something specific, so I don't expect anyone to be able to give you one "answer" to solve the problem. – Emre Bener Jun 05 '23 at 13:33
  • @Mephisto I am going to produce a version that uses the Azure identity platform for sure. I tried an implementation using Duende and it was horrendously difficult to get it to work reliably. I have had all sorts of issues with it, and as I don't have any hair left to tear out, have gone with this approach instead. Still I'll have a look at your link. – Philip Johnson Jun 12 '23 at 17:56

3 Answers3

0

You can check the thread below first, I have double confirmed it is you wanted.

How to share a session values between an ASP.NET and ASP.NET Core application?

You need to follow the steps to modify the code in this repo. You can check the test result.

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • Thanks, I'm having a look now, I don't think I use sessions though (unless ASP.NET identity is adding them somehow). – Philip Johnson May 30 '23 at 13:53
  • This doesn't help I'm afraid, as I'm using asp.net identity not sessions – Philip Johnson May 31 '23 at 08:52
  • @PhilipJohnson If you could share the minimal sample for me, I am willing to investigate the issue further. Pls don't forget hide your sensitive information. – Jason Pan May 31 '23 at 08:55
  • Thank for the offer Jason, I don't have one and am leaving work in 5 minutes... I have been looking at this, I'll try this and if I'm still struggling may take you up... https://github.com/dotnet/AspNetCore.Docs/issues/21987 – Philip Johnson May 31 '23 at 10:57
  • sessions and cookies are two different things. – Emre Bener Jun 05 '23 at 13:21
  • @JasonPan, I have finally managed to create my example, which appears to work. If you would like to have a look and send me any comments I would very much appreciate it. The link to github is in my description above. – Philip Johnson Jun 12 '23 at 17:54
0

ASP.NET 4.x apps that use Microsoft.Owin Cookie Authentication Middleware can be configured to generate authentication cookies that are compatible with the ASP.NET Core Cookie Authentication Middleware. This can be useful if a web application consists of both ASP.NET 4.x apps and ASP.NET Core apps that must share a single sign-on experience. A specific example of such a scenario is incrementally migrating a web app from ASP.NET to ASP.NET Core. In such scenarios, it's common for some parts of an app to be served by the original ASP.NET app while others are served by the new ASP.NET Core app. Users should only have to sign in once, though. This can be accomplished by either of the following approaches:

Using the System.Web adapters' remote authentication feature, which uses the ASP.NET app to sign users in.

Configuring the ASP.NET app to use Microsoft.Owin Cookie Authentication Middleware so that authentication cookies are shared with the ASP.NET Core app.

https://learn.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-7.0#share-authentication-cookies-between-aspnet-4x-and-aspnet-core-apps

Will work when implemented like is written in MS documentation.

K Paul
  • 1
  • 2
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 02 '23 at 08:51
  • Thanks I don't think that documentation is up to date. The libraries it refers to have been deprecated. – Philip Johnson Jun 05 '23 at 15:59
  • @PhilipJohnson this is normal, because the package targeting .NET Framework 4.6.1 and this version is end-of-life. Then all packages without updates will be automatically turn in to depricated. You can read here about: https://github.com/dotnet/announcements/issues/217 But as temporary solution is worth to try. – K Paul Jun 05 '23 at 20:55
0

Thought I'd post an alternative design option that might interest you, if you are evaluating new technology and possibly open to such ideas. It involves issuing cookies using a .NET utility API, that is shared by multiple frontends.

This enables frontends to be coded in a pure web technology such as React. It also enables frontends to share cookies without conflicts. As an example, you could host components like this:

The oauth-client issues the cookies. A reverse proxy or API gateway can be used to route to each backend component, and keep code bases small and separated. Web specific security handling, such as translating from cookies to tokens, can also be handled at the gateway.

For an example, see my demo SPA. Pros are the improved architectural choices it gives you. Cons are that the greater separation can make deployment and developer setups trickier.

Gary Archer
  • 22,534
  • 2
  • 12
  • 24