我们有一个自定义的cookie身份验证提供程序,将auth cookie设置为像
问题:
在应用程序冷启动后的第一次尝试中,即使在执行下面的
问题:
如何修复此问题,以便即使在第一次尝试时也能正常工作?
代码:
自定义cookie auth
.domain.com
这样的主机名,而不是domain.com
或my.domain.com
。我们这样做是为了使cookie在所有子域和域之间工作。如下所示,它非常简单。问题:
在应用程序冷启动后的第一次尝试中,即使在执行下面的
SubdomainCookieAuthentication
代码之后(使用断点检查),cookie仍然带有my.domain.com
的域名(我们的登录在my.domain.com
上)。在随后的登录尝试中,cookie主机名是正确的。问题:
如何修复此问题,以便即使在第一次尝试时也能正常工作?
代码:
自定义cookie auth
public class SubdomainCookieAuthentication : CookieAuthenticationProvider
{
public override void ResponseSignIn(CookieResponseSignInContext context)
{
// We need to add a "." in front of the domain name to
// allow the cookie to be used on all sub-domains too
var hostname = context.Request.Uri.Host;
// works for www.google.com => google.com
// will FAIL for www.google.co.uk (gives co.uk) but doesn't apply to us
var dotTrimmedHostname = Regex.Replace(hostname, @"^.*(\.\S+\.\S+)", "$1");
context.Options.CookieDomain = dotTrimmedHostname;
base.ResponseSignIn(context);
}
}
这是在Owin启动类中进行初始化的,具体步骤如下:
类:Startup
文件:App_start\Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new SubdomainCookieAuthentication()
});
}