ASP.NET Identity Cookie Across Subdomains

ASP.NET Identity Cookie across subdomains

In Startup.Auth.cs, you will see something like:

for RC:

app.UseSignInCookies();

This was removed in RTM and replaced with the explicit configuration of the cookie auth:

    app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});

The CookieAuthenticationOptions class has a CookieDomain property which is what you are looking for I believe.

ASP.NET Identity Cookie across subdomains on .Net and Core

I got solution from this Microsoft documentation

Share cookies among apps with ASP.NET and ASP.NET Core

And Sample code for this sub-domain authentication system

Cookie Sharing Sample App - GitHub

The sample illustrates cookie sharing across three apps that use cookie authentication:

  • ASP.NET Core 2.0 Razor Pages app without using ASP.NET Core Identity
  • ASP.NET Core 2.0 MVC app with ASP.NET Core Identity
  • ASP.NET Framework 4.6.1 MVC app with ASP.NET Identity

Put this code in your ConfigureServices method in Startup.cs

services.AddDataProtection()
.PersistKeysToFileSystem(GetKeyRingDirInfo())
.SetApplicationName("example");

services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "example";
options.Cookie.Domain = ".example.com";
});

For KeyRing method

private DirectoryInfo GetKeyRingDirInfo()
{
var startupAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var applicationBasePath = System.AppContext.BaseDirectory;
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
directoryInfo = directoryInfo.Parent;

var keyRingDirectoryInfo = new DirectoryInfo(Path.Combine(directoryInfo.FullName, "KeyRing"));
if (keyRingDirectoryInfo.Exists)
{
return keyRingDirectoryInfo;
}
}
while (directoryInfo.Parent != null);

throw new Exception($"KeyRing folder could not be located using the application root {applicationBasePath}.");
}

Note : You have to copy KeyRing file which is automatically generated on Identity application hosting server and manually paste to other sub-domain and main domain hosting server of other website to share cookie for authentication.

Sharing the Identity Login Cookie across subdomains

So it was a bit more complicated in some ways, but the solution is actually pretty simple.

Localhost gets special treatments in a lot of ways, but also for cookies. In order for a cookie to be accepted by the client e.g. the browser the Domain property needs to contain at least two dots. For localhost you can simple do this by constructing your domain something like .domain.localhost which will solve the issue. Of course you will need to call your website now over the same domain in order to work.

Share authentication cookie across subdomains in ASP.NET Core - cannot login

Solved! When using custom domain, everything runs as expected

MVC Identity cookie is authenticated across subdomains

You must build an identity server to login with SSO.

You can find details here

Multiple & SubDomain's cookie in asp.net Core Identity

What I didnt realise when I started was the difference between Identity and CookieAuthentication.
Since I was using Identity

        app.UseIdentity();

app.UseCookieAuthentication was not the solution.

I finally found my solution by implementing ICookieManager.

Here is my solution:

in Startup.cs:

    services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 5;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Cookies.ApplicationCookie.CookieManager = new CookieManager(); //Magic happens here
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

now in a class I have called CookieManager.cs:

public class CookieManager : ICookieManager
{
#region Private Members

private readonly ICookieManager ConcreteManager;

#endregion

#region Prvate Methods

private string RemoveSubdomain(string host)
{
var splitHostname = host.Split('.');
//if not localhost
if (splitHostname.Length > 1)
{
return string.Join(".", splitHostname.Skip(1));
}
else
{
return host;
}
}

#endregion

#region Public Methods

public CookieManager()
{
ConcreteManager = new ChunkingCookieManager();
}

public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
{

options.Domain = RemoveSubdomain(context.Request.Host.Host); //Set the Cookie Domain using the request from host
ConcreteManager.AppendResponseCookie(context, key, value, options);
}

public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
ConcreteManager.DeleteCookie(context, key, options);
}

public string GetRequestCookie(HttpContext context, string key)
{
return ConcreteManager.GetRequestCookie(context, key);
}

#endregion

ASP.NET Identity cookie and subdomains

After a lot of headscratching I noticed i difference in version numbers in various Identity packages. I updated the various packages from Nuget, and wouldn't you know. It worked!

What worries me is that it only updated from minor versions (e.g. Microsoft.Owin.Security.Cookies from 3.0.0.0 to 3.0.1.0). I don't hope they have to stay aligned like that in the future..



Related Topics



Leave a reply



Submit