I have many application which is hosted on main domain and sub domains:
Website A, ASP.NET (.Net Core 2.0) at www.example.com
Website B, ASP.NET MVC (4.7 .net Framework) at site.example.com
Website C, ASP.NET Identity (.Net Core 2.0) at account.example.com
Website D, ASP.NET Webform (4.7 .net Framework) at file.example.com
I would like to login uses on account.example.com, after authenticate users will redirected to other websites. They will be authorize by there roles on other websites.
I'm trying to share a cookie between these websites and all of the website are hosted on Azure Web App.
I am using ASP.NET Identity (.Net Core 2.0). I'm using the built-in cookie authentication.
How can I use Data Protection in all application and share cookie among them.
For Data Protection my code is:
services.AddDataProtection()
.SetApplicationName("example")
.PersistKeysToFileSystem(new DirectoryInfo(@"%HOME%\ASP.NET\DataProtection-Keys"))
.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
For Cookie Authentication my code is:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
CookieDomain = ".example.com"
});
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:
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.