mic*_*ael 7 asp.net-identity asp.net-core-mvc asp.net-core
我有一个网页,它为同一个应用程序使用多个URL:
例如:*.MyWebPage.com.au*.YourWebPage.com.au
因此它将在多个网址上使用子域名.问题是我需要允许用户在他们登录的URL的所有子域上进行身份验证.
例如,如果他们通过www.mywebpage.com.au登录,则需要为*.mywebpage.com.au设置cookie,或者如果他们通过www.yourwebpage.com.au登录,则cookie应为*.yourwebpage.com. AU.
允许ASP.NET核心标识的子域的大多数文档都指向startup.cs(或startup.auth.cs)文件并输入如下内容:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieDomain = "mywebpage.com.au"
});`
Run Code Online (Sandbox Code Playgroud)
这对我不起作用,因为我不想要一个固定的域名,我只想让所有用户都可以访问他们登录的URL的所有子域名.我可以通过请求显然在登录时获取他们的URL,但我需要动态设置cookiedomain.
我开始时没想到的是Identity和CookeieAuthentication之间的区别.因为我使用的是身份
app.UseIdentity();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
现在我在一个叫做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
Run Code Online (Sandbox Code Playgroud)
除了@michael 的解决方案:
ICookie:ICookie Interface是 之上的抽象层http cookie object,它保护data.ICookieManager:Cookie Manager是在ICookie Interface. 这在<TSource>通用支持方面扩展了 Cookie 行为,Func<TResult>这是由DefaultCookieManager类实现的。ICookie Interface是这个类的依赖。用法CookieManager:
CookieManager在启动配置服务中添加。git通过内米昌。| 归档时间: |
|
| 查看次数: |
4414 次 |
| 最近记录: |