To get an overview, I have an old .NET Framework 4.7.2 Website with a lot of .aspx Files and I have a new .NET Core WebApp. Both are running on the same server under the same domain with different ports.
I now want to login into the .NET Core Website and be able to use the Authentication Token on the .NET Framework Website too. I tried to use the Cookie generated by the .NET Core Website to Authenticate on the .NET Framework Website with Owin, but I couldn't find any way to get this to work.
Does anyone have an Idea on how to accomplish this? I need to authenticate once and be able to stay Authenticated over both websites.
CodePudding user response:
To share authentication cookies between your ASP.NET 4.x applications and your ASP.NET Core applications, firstly, configure the ASP.NET Core application by following the steps:
Add Authentication to your app
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(); //other services... }In your
Configuremethod use theCookieAuthenticationOptionsto set up the data protection service for cookiesapp.UseCookieAuthentication(new CookieAuthenticationOptions { DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\")) });
Then configure your ASP.NET 4.7.2 application by following steps below:
Install the package
Microsoft.Owin.Security.Interopinto your ASP.NET 4.7.2 application.In
Startup.Auth.cs, locate the call toUseCookieAuthentication, which will generally look like the following:app.UseCookieAuthentication(new CookieAuthenticationOptions { // ... });Modify the call to
UseCookieAuthenticationas follows, changing theAuthenticationTypeandCookieNameto match those of the ASP.NET Core cookie authentication middleware, and providing an instance of a DataProtectionProvider that has been initialized to a key storage location.app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies", CookieName = ".AspNetCore.Cookies", // CookiePath = "...", (if necessary) // ... TicketDataFormat = new AspNetTicketDataFormat( new DataProtectorShim( DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\")) .CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2"))) });
The DirectoryInfo has to point to the same storage location that you pointed your ASP.NET Core application to and should be configured using the same settings.
In
IdentityModels.cs, change the call toApplicationUserManager.CreateIdentityto use the same authentication type as in the cookie middleware.public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = manager.CreateIdentity(this, "Cookies"); // ... }
Reference:
Share authentication cookies among ASP.NET apps
Share authentication cookies between ASP.NET 4.x and ASP.NET Core apps
