Search code examples
cookiesasp.net-identityowin

Variable cookie path with ASP.NET Identity


We migrated a multitenant MVC application from ASP.NET Membership Provider to ASP.NET Identity.

This is my Startup.Auth.cs (simplified):

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity =
                    SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, Identity, int>(
                        TimeSpan.FromMinutes(30),
                        (manager, user) =>
                            manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie),
                        clIdentity => clIdentity.GetUserId<int>())
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}

In our multitenant application, each tenant has its own 'slug' (e.g. http://example.com/tenant1/ and http://example.com/tenant2/)

However, currently, the cookies are stored in the root. This causes security issues as users from tenant1 are automatically logged in on the website from tenant2.

How can we make the CookiePath (in CookieAuthenticationOptions) variable so that it changes depending on the tenant?


Solution

  • I fixed this issue with a lot of help from dampee.

    The CookiePath in the CookieAuthenticationOptions object is evaluated only once: at application startup. The easiest solution (workaround) was to create a derived CookieAuthenticationProvider that overrides ResponseSignIn and ResponseSignOut. They both have an argument called context which has a property called CookiePath. Modify this property in both of these methods to change the CookiePath. You can also use the class I created.

    Then all you have to do is replace the CookieAuthenticationProvider in the CookieAuthenticationOptions with the one you just created.

    This works for the ApplicationCookie. The ExternalSignInCookie doesn't matter that much since it is used only temporarily while signing in with an external login.