ASP的可变cookie路径.NET标识



我们从ASP迁移了一个多租户MVC应用程序。NET成员资格提供程序到ASP。NET标识。

这是我的创业。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);
}

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

然而,目前,cookie存储在根目录中。这会导致安全问题,因为tenant1的用户会自动从tenant2登录到网站。

我们如何使CookiePath(在CookieAuthenticationOptions中)变量根据租户的不同而变化

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

CookieAuthenticationOptions对象中的Cookie路径仅评估一次:在应用程序启动时。最简单的解决方案(解决方法)是创建一个派生的CookieAuthenticationProvider,它覆盖ResponseSignInResponseSignOut。它们都有一个名为context的参数,该参数有一个称为CookiePath。在这两种方法中都修改此属性以更改Cookie路径。您也可以使用我创建的类。

然后,您所要做的就是将CookieAuthenticationOptions中的Cookie AuthenticationProvider替换为您刚刚创建的。

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

改进SamuelDebruyn自己的解决方案,我发现可以使用AuthenticationProperties对象将SignIn调用的路径传递给提供者。通过这种方式,您可以从源显式地传递路径,而不是像他的要点所示的那样从请求上下文中提取路径:

// method inside web api controller
private void SignIn(string name, string cookiePath)
{
    var claims = new[] { new Claim(ClaimTypes.Name, name) };
    var identity = new ClaimsIdentity(claims, "ApplicationCookie");
    var options = new AuthenticationProperties();
    options.Dictionary["CustomCookiePath"] = cookiePath;
    var authManager = Request.GetOwinContext().Authentication;
    authManager.SignIn(options, identity);
}
// Startup.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    Provider = new CustomCookieProvider()
});
// custom provider
public class CustomCookieProvider : CookieAuthenticationProvider
{
    public override void ResponseSignIn(CookieResponseSignInContext context)
    {
        context.CookieOptions.Path = context.Properties.Dictionary["CustomCookiePath"];
        base.ResponseSignIn(context);
    }
}

您可以使用自定义ICookieManager根据请求中的内容动态地将cookie值返回给CookieAuthenticationProvider,为此,您仍然需要将CookiePath保持为"/",然后让ICookieManager根据您的意愿返回(或写入)cookie。CookieManagerCookieAuthenticationOptions上的一个选项。我在这里写了一篇博客:http://shazwazza.com/post/owin-cookie-authentication-with-variable-cookie-paths/

最新更新