ASP.NET身份的可变cookie路径

Sam*_*uyn 6 cookies owin asp.net-identity

我们将多租户MVC应用程序从ASP.NET成员资格提供程序迁移到ASP.NET Identity.

这是我的Startup.Auth.cs(简化):

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);
}
Run Code Online (Sandbox Code Playgroud)

在我们的多租户应用程序中,每个租户都有自己的"slug"(例如http://example.com/tenant1/http://example.com/tenant2/)

但是,目前,cookie存储在根目录中.这会导致安全问题,因为来自tenant1的用户会自动从tenant2登录网站.

我们如何使CookiePath(在CookieAuthenticationOptions中)变量,以便它根据租户而变化?

Sam*_*uyn 6

我在dampee的帮助下解决了这个问题.

CookiePathCookieAuthenticationOptions对象只计算一次:在应用程序启动.最简单的解决方案(解决方法)是创建一个派生的CookieAuthenticationProvider,它覆盖ResponseSignInResponseSignOut.它们都有一个名为context的参数,它有一个名为CookiePath的属性.在这两种方法中修改此属性以更改CookiePath.您也可以使用我创建的类.

然后,您所要做的就是将CookieAuthenticationOptions中的CookieAuthenticationProvider替换为刚创建的CookieAuthenticationProvider.

这适用于ApplicationCookie.ExternalSignInCookie并不重要,因为它只是在使用外部登录登录时暂时使用.