Search code examples
c#asp.net-mvcasp.net-corecookiesasp.net-identity

How to use an MVC .NET Core authentication cookie in another project on the same domain


We have a server in our company that runs IIS and we access it via an IP address inside the network. There are multiple projects in the root folder. These are all MVC ASP .NET CORE 2 web apps.

One of these projects is kind of a hub web app that has links to other projects. What I need to do, is the following:

  1. User logs in at the hub web app that uses Microsoft.AspNetCore.Identity and Microsoft.AspNetCore.Authorization.
  2. The user clicks a link that takes him to a different app. (It works up until this point, obviously.)
  3. This app's controller is locked down under the [Authorize] tag. And I want this app to recognize that the user is already logged in and use the Authorization cookie to authorize them in the whole app.

The cookie is still present when the user accesses the second app, but I don't know how to use the cookie from the Hub app. I guess I will need to have the DBContext with the Identity SQL Database in there and use the cookie somehow to authenticate.

I am new to .NET Core after years of PHP and I am truly desperate now.

Thank you to anyone who at least reads this. Cheers!


Solution

  • If you want both the sites/apps to use a same authentication mechanism then you can set a common machine key for both the app. Then the second app will automatically pickup the authorized users from the first app.

    Here is how to set the machine key:

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddDataProtection().DisableAutomaticKeyGeneration();
    }
    

    Sample code picked from here: https://stackoverflow.com/a/46894509/218408

    More details: Machine key in asp.net core 2.0?

    Update:

    Here is how to set the machine key and others based on your authentication mechanism:

    services.AddDataProtection()
        .PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")
        .SetApplicationName("SharedCookieApp");
    
    services.ConfigureApplicationCookie(options => {
        options.Cookie.Name = ".AspNet.SharedCookie";
        options.Cookie.Path = "/";
    });
    

    Read more here: https://learn.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-3.0