正确创建跨域表单身份验证cookie

7 asp.net cookies forms-authentication

我只是在两个服务器之间创建一个简单的测试.基本上,如果用户已经过身份验证,我希望能够在应用程序之间传递它们.我改变了键来隐藏它们

我有三个问题:

  1. 跨域应用程序验证cookie的正确方法是什么.例如,当用户登陆successpage.aspx我应该检查什么时?
  2. 以下代码是否对创建跨域身份验证cookie有效?
  3. 我的web.config设置是否正确?

我的代码:

if (authenticated == true)
{
  //FormsAuthentication.SetAuthCookie(userName, false);
  bool IsPersistent = true;
  DateTime expirationDate = new DateTime();
  if (IsPersistent)
    expirationDate = DateTime.Now.AddYears(1);
  else
    expirationDate = DateTime.Now.AddMinutes(300); 

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
      1,
      userAuthName,
      DateTime.Now,
      expirationDate,
      IsPersistent,
      userAuthName,
      FormsAuthentication.FormsCookiePath);

  string eth = FormsAuthentication.Encrypt(ticket);
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, eth);
  if (IsPersistent)
    cookie.Expires = ticket.Expiration;

  cookie.Domain = ".myDomain.com";
  Response.SetCookie(cookie);
  Response.Cookies.Add(cookie);

  Response.Redirect("successpage.aspx");
}
Run Code Online (Sandbox Code Playgroud)

我的配置:

<authentication mode="Forms">
  <forms loginUrl="~/Default.aspx" timeout="2880" name=".AUTHCOOKIE" domain="myDomain.com" cookieless="UseCookies" enableCrossAppRedirects="true"/>
</authentication>
<customErrors mode="Off" defaultRedirect="failure.aspx" />
<machineKey decryptionKey="@" validationKey="*" validation="SHA1"  decryption="AES"/>
Run Code Online (Sandbox Code Playgroud)

jbl*_*jbl 4

跨域应用程序验证 cookie 的正确方法是什么?例如,当用户登陆 successpage.aspx 时,我应该检查什么?

应该没有什么可检查的。Forms 身份验证机制将从 cookie 中检索票证,检查其是否有效。如果不存在或无效,用户将重定向到 ~/Default.aspx 。如果您的 cookie 与 web.config 的配置匹配,这将起作用

下面的代码对于创建跨域身份验证 cookie 是否有效?

我认为您不应该尝试通过手动处理 cookie 来覆盖 web.config 的设置。我认为有更好的方法来处理 cookie 持久性(请参阅下面的 web.config),并且您只是实现 Forms 身份验证 API 的一部分(例如,丢失 SSL 的 web.config )

  1. 在这里,您的手动 cookie 不是 HttpOnly :例如,您可能会通过 XSS 遭受 cookie 盗窃
  2. FormsAuthentication 有自己的处理 cookie 的方式(请参阅http://msdn.microsoft.com/en-us/library/1d3t3c61%28v=vs.80%29.aspx中的 TimeOut 属性描述)您的 cookie 持久机制将是被这种自动行为覆盖

你的代码应该是:

if (authenticated)
{  
  bool isPersistent = whateverIwant;
  FormsAuthentication.SetAuthCookie(userName, isPersistent );
  Response.Redirect("successpage.aspx");
}
Run Code Online (Sandbox Code Playgroud)

我的 web.config 设置正确吗?

对于domain属性应该没问题,只要你想在mydomain.com的直接子域之间共享身份验证(它不适用于xymydomain.com),并且mydomain.com不在公共后缀列表中(http: //publicsuffix.org/list/ )

我会将超时和滑动过期属性更改为:

 <forms loginUrl="~/Default.aspx" timeout="525600" slidingExpiration="false" name=".AUTHCOOKIE" domain="myDomain.com" cookieless="UseCookies" enableCrossAppRedirects="true"/>
Run Code Online (Sandbox Code Playgroud)

我想这是处理一年持久 cookie 和会话 cookie 之间选择的好方法。有关更多信息,请参阅/sf/answers/262410641/