跨子域的Asp.NET cookie未更新且未过期

时间:2010-02-18 22:00:02

标签: cookies subdomain

我有2个子域名,我需要从两个网站设置和读取相同的cookie。

当我使用localhost时,一切正常。

当我切换到使用有效网址时,我更新时,cookie信息并未真正更新(注销时过期日期)。

我将Cookie的域名设置为“.mysite.com”

出了什么问题?

4 个答案:

答案 0 :(得分:1)

答案是在退出时将域设置为cookie

HttpCookie aCookie = Request.Cookies["Token"];
aCookie.Expires = DateTime.Now.AddDays(-1);
aCookie.Domain = ConfigurationManager.AppSettings["CookieDomain"];
Response.Cookies.Add(aCookie);

答案 1 :(得分:0)

这是我的代码:(在localhost上工作正常,但不是子域,从不将用户注销,因为cookie没有过期)

登录页面:

  FormsAuthentication.SetAuthCookie(UserName.Text, true);
    // set the active collab cookie
    Member member = MemberManager.GetMemberByUsername(UserName.Text);

    HttpCookie cookie = new HttpCookie("Token", member.Profile.Token);
    cookie.Domain = ConfigurationManager.AppSettings["CookieDomain"];
    cookie.Expires = DateTime.Now.AddYears(1);
    Response.Cookies.Add(cookie);

Globax ASAX

if (HttpContext.Current.Request.Cookies["Token"] != null) {
        string token = HttpContext.Current.Request.Cookies["Token"].Value;
        if (!string.IsNullOrEmpty(token)) {
                // If the user is logged in with a different token
                // or not logged in at all
                // then log them in with the token from the cookie
                if ((MemberManager.CurrentMember != null && MemberManager.CurrentMember.Profile.Token != token) || User == null) {

                  Member member = MemberManager.GetMemberByToken(token);
                  if (member != null) {
                        FormsAuthentication.SetAuthCookie(member.User.UserName, true);
                 }
             }
                }
            }

退出代码:

 if (Request.Cookies["Token"] != null) {
                HttpCookie aCookie = Request.Cookies["Token"];
                aCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(aCookie);
}

的Web.Config

 <machineKey
      validationKey="{-snip-}"
      decryptionKey="{-snip-}"
      validation="SHA1"
      decryption="AES" />

 <authentication mode="Forms">
      <forms name="AuthCookie"
             path="/"
             loginUrl="~/login.aspx"
             protection="All"
             timeout="60">
      </forms>
    </authentication>

答案 2 :(得分:0)

试试这个:

 if (Request.Cookies["Token"] != null) {
                HttpCookie aCookie = Request.Cookies["Token"];
                aCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["Token"] = aCookie;
}

不是添加它,而是将其设置为现有的cookie。

答案 3 :(得分:0)

web.config中的表单身份验证设置需要启用跨应用程序重定向:

<authentication mode="Forms">
    <forms loginUrl="~/login.aspx" protection="All" timeout="960" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="false" defaultUrl="~/default.aspx" enableCrossAppRedirects="true"/>
</authentication>