gpt4 book ai didi

asp.net-core - asp.net Core Identity 中的 Multiple & SubDomain cookie

转载 作者:行者123 更新时间:2023-12-03 18:18:10 25 4
gpt4 key购买 nike

我有一个网页,它对同一个应用程序使用多个 URL:

例如:
*.MyWebPage.com.au
*.YourWebPage.com.au

所以它将在多个 url 上使用子域。问题是我需要允许用户在他们登录的 url 的所有子域上进行身份验证。

例如,如果他们通过 www.mywebpage.com.au 登录,则需要为 *.mywebpage.com.au 设置 cookie,或者如果他们通过 www.yourwebpage.com.au 登录,则 cookie 应为 *.yourwebpage.com。澳

大多数允许 ASP.NET 核心标识的子域的文档都指向 startup.cs(或 startup.auth.cs)文件并输入如下内容:`

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieDomain = "mywebpage.com.au"
});`

这对我不起作用,因为我不想要固定域,我只想允许所有用户访问他们登录的 url 的所有子域。我显然可以在通过请求登录时获取他们的 url,但此时我需要动态设置 cookiedomain。

最佳答案

刚开始的时候没想到的是 Identity 和 CookieAuthentication 的区别。
因为我使用的是 Identity

        app.UseIdentity();

app.UseCookieAuthentication 不是解决方案。

我终于通过实现 ICookieManager 找到了我的解决方案。

这是我的解决方案:

在 Startup.cs 中:
    services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 5;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Cookies.ApplicationCookie.CookieManager = new CookieManager(); //Magic happens here
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

现在在我称为 CookieManager.cs 的类中:
public class CookieManager : ICookieManager
{
#region Private Members

private readonly ICookieManager ConcreteManager;

#endregion

#region Prvate Methods

private string RemoveSubdomain(string host)
{
var splitHostname = host.Split('.');
//if not localhost
if (splitHostname.Length > 1)
{
return string.Join(".", splitHostname.Skip(1));
}
else
{
return host;
}
}

#endregion

#region Public Methods

public CookieManager()
{
ConcreteManager = new ChunkingCookieManager();
}

public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
{

options.Domain = RemoveSubdomain(context.Request.Host.Host); //Set the Cookie Domain using the request from host
ConcreteManager.AppendResponseCookie(context, key, value, options);
}

public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
ConcreteManager.DeleteCookie(context, key, options);
}

public string GetRequestCookie(HttpContext context, string key)
{
return ConcreteManager.GetRequestCookie(context, key);
}

#endregion

关于asp.net-core - asp.net Core Identity 中的 Multiple & SubDomain cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com