Cookies 具有ASP.NET标识的可变cookie路径
我们将多租户MVC应用程序从ASP.NET成员资格提供程序迁移到ASP.NET标识 这是我的Startup.Auth.cs(简化):Cookies 具有ASP.NET标识的可变cookie路径,cookies,asp.net-identity,owin,Cookies,Asp.net Identity,Owin,我们将多租户MVC应用程序从ASP.NET成员资格提供程序迁移到ASP.NET标识 这是我的Startup.Auth.cs(简化): 公共部分类启动 { public void ConfigureAuth(IAppBuilder应用程序) { app.CreatePerOwinContext和) 但是,当前cookie存储在根目录中。这会导致安全问题,因为租户1的用户会从租户2自动登录网站 如何使CookiePath(在CookieAuthenticationOptions中)变量根据租户的不同
公共部分类启动
{
public void ConfigureAuth(IAppBuilder应用程序)
{
app.CreatePerOwinContext和)
但是,当前cookie存储在根目录中。这会导致安全问题,因为租户1的用户会从租户2自动登录网站
如何使CookiePath(在CookieAuthenticationOptions中)变量根据租户的不同而变化?我在来自的大量帮助下解决了这个问题
CookieAuthenticationOptions对象中的CookiePath只计算一次:在应用程序启动时。
最简单的解决方案(解决方法)是创建一个派生的CookieAuthenticationProvider,它覆盖ResponseSignIn和ResponseSignOut。
它们都有一个名为context的参数,该参数有一个名为CookiePath的属性。在这两个方法中修改此属性以更改CookiePath。
你也可以
然后,您所要做的就是将CookieAuthenticationOptions中的CookieAuthenticationProvider替换为您刚刚创建的
这适用于ApplicationOkie。ExternalSigningOkie并不重要,因为它仅在使用外部登录登录时临时使用。改进了SamuelDebruyn自己的解决方案,我发现您可以使用AuthenticationProperties
对象将SignIn调用的路径传递给提供者正如他的要点所示,您可以从源显式地传递路径,而不是从请求上下文中提取路径:
//web api控制器中的方法
私有void签名(字符串名称、字符串路径)
{
var claims=new[]{new claims(ClaimTypes.Name,Name)};
var标识=新的索赔实体(索赔,“申请书”);
var options=newauthenticationproperties();
options.Dictionary[“CustomCookiePath”]=cookiePath;
var authManager=Request.GetOwinContext().Authentication;
authManager.sign(选项、标识);
}
//Startup.cs
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
Provider=新的CustomCookieProvider()
});
//自定义提供者
公共类CustomCookieProvider:CookieAuthenticationProvider
{
public override void ResponseSignIn(CookiierResponsesignin上下文)
{
context.CookieOptions.Path=context.Properties.Dictionary[“CustomCookiePath”];
基础反应素(上下文);
}
}
您可以使用自定义的ICookieManager
根据请求中的任何内容动态地将cookie值返回给CookieAuthenticationProvider
,为此,您仍需将CookiePath保持为“/”,然后由ICookieManager
返回(或写入)cookie是你想要的。CookieManager是CookieAuthenticationOptions上的一个选项。我在这里写了一篇博客:
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);
}