FormsAuthentication.SetAuthCookie没有设置路径或域?

Kei*_*ith 7 asp.net cookies forms-authentication

我有一个Web应用程序可以安装在很多域和路径上.

所以:

  • client1Name.{mySite.com}
  • client2Name.{mySite.com}
  • 演示.{mySite.com}/prospect1Name
  • 演示.{mySite.com}/prospect2Name
  • 演示.{mySite.com}/prospect3Name

所有相同代码的单独应用程序实例.

问题是如果客户端登录到client1Name.{mySite.com}然后访问其他站点之一,他们的浏览器将发送身份验证cookie.

在所有的情况下,FormsAuthentication.SetAuthCookie不设置任何的PathDomain.

我期望的是:

  • client1Name.{mySite.com} - Domain= client1Name.{mySite.com} Path = /
  • client2Name.{mySite.com} - Domain= client2Name.{mySite.com} Path = /
  • demo.{mySite.com}/prospect1Name - Domain= demo.{mySite.com} Path = / prospect1Name
  • demo.{mySite.com}/prospect2Name - Domain= demo.{mySite.com} Path = / prospect2Name
  • demo.{mySite.com}/prospect3Name - Domain= demo.{mySite.com} Path = / prospect3Name

我可以手动覆盖.Net的行为以显式设置这些,但我不确定为什么我需要 - 确保这应该是设置身份验证cookie时的默认行为,或者至少是一个可以在不重写的情况下设置的选项大块的.

我错过了什么吗?是否有某种方法可以FormsAuthentication.SetAuthCookie设置PathDomain

如果没有什么是动态阅尽的最佳方式PathDomain?必须在所有站点上运行相同的代码,我不想添加其他配置密钥.

更新

这是我目前的解决方案:

// replacement for FormsAuthentication.SetAuthCookie(user.UserName, false);
// as that fails to limit the cookie by domain & path and fails.

var cookie = FormsAuthentication.GetAuthCookie(username, false);
cookie.HttpOnly = true;
cookie.Path = this.Request.ApplicationPath;
cookie.Secure = string.Equals("https", this.Request.Url.Scheme, StringComparison.OrdinalIgnoreCase);

// the browser will ignore the cookie if there are fewer than two dots
// see cookie spec - http://curl.haxx.se/rfc/cookie_spec.html
if (this.Request.Url.Host.Split('.').Length > 2)
{
    // by default the domain will be the host, so www.site.com will get site.com
    // this may be a problem if we have clientA.site.com and clientB.site.com
    // the following line will force the full domain name
    cookie.Domain = this.Request.Url.Host;
}

this.Response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

但是,对于某些东西FormsAuthentication.SetAuthCookie应该能够做的事情似乎很多.这真的是最好的方式吗?

Kei*_*ith 8

我不得不做很多挖掘,但看起来FormsAuthentication.SetAuthCookie不支持这个原因是因为它不应该 - IIS 永远应该在认证cookie上设置路径,这就是为什么......

Cookie路径区分大小写,因此:

  • http://site/path
  • http://site/PATH

浏览器有2种不同的cookie - 它们(IE,FX,Safari,Opera或Chrome)都不会发送/PATHcookie,/path反之亦然.

IIS 不区分大小写,但始终将URL重置为ASP应用程序名称的大小写.

这意味着如果IIS应用程序被称为"PATH"并且用户转到http://site/path那么它们将被重定向到http://site/PATH/LogOn?ReturnUrl=/pathIIS/ASP.Net 登录

登录成功后,用户将被重定向回ReturnUrl指定的,因此:

  1. 用户去了 http://site/path
  2. http://site/PATH/LogOn?ReturnUrl=/path由IIS 发送
  3. 输入登录详细信息和提交
  4. 响应将cookie设置为/PATH/path(由定义的ReturnUrl)位置
  5. 重定向回 http://site/path
  6. 浏览器无法识别/path,它只有一个cookie /PATH,所以什么都不发送!
  7. 没有cookie发送到应用程序,因此它提供重定向 http://site/PATH/LogOn?ReturnUrl=/path
  8. 转到步骤2并重复.

如果用户具有http://site/path他们永远不会登录的应用程序的URL,则会给用户带来问题.

除此之外,如果他们已经登录http://site/PATH并发送了一个URL,比如发送一封电子邮件给http://site/path/resource/id他们,他们将被要求重新登录,并且无法进入新路径.

这意味着除非您需要/PATH并且/path是完全不同的站点(不太可能在某些仅UNIX环境之外),否则不应在身份验证cookie上设置路径属性.