實現Cookie跨域共享


實現原理:cookie是不能跨域訪問的,但是在二級域名是可以共享cookie的

概念說明:站點1=a.abc.com   站點2=b.abc.com

實現步驟:1. 配置兩個站點的webconfig

              2. a.abc.com寫入cookie 

              3. b.abc.com讀取cookie

一、配置Webconfig:

<httpRuntime targetFramework="4.0" />     

    我用的vs2012,默認生成的targetFramework=4.5 不知道為什么 4.5就不能跨域,有知道的朋友請指教。

<authentication mode="Forms">
     <forms domain="abc.com" name="abc.authcookie" protection="None" />
</authentication>

    測試了N久,這三個屬性少一個都不能訪問。兩個站點的authentication配置是一樣的。

二、站點1寫入cookie

      //利用asp.net中的form驗證加密數據,寫入Cookie
      private HttpCookie GetAuthCookie(string userData, string userName)
     {

           //登錄票證
           FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
              3,
              userName,
              DateTime.Now,
              DateTime.Now.AddMinutes(100000),
              false,
              userData,
              FormsAuthentication.FormsCookiePath  //可在webconfig中設置 默認為/
           );

           string encTicket = FormsAuthentication.Encrypt(ticket);

           if ((encTicket == null) || (encTicket.Length < 1))
          {
                throw new HttpException("Unable_to_encrypt_cookie_ticket");
          }
          
          HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
          cookie.Path = "/";
          cookie.HttpOnly = true;  //是否可通過腳本訪問 設置為true 則不可通過腳本訪問
          cookie.Domain = FormsAuthentication.CookieDomain;  //webconfig中設置的domain
          //cookie.Secure = FormsAuthentication.RequireSSL;  //當此屬性為 true 時,該 Cookie 只能通過 https:// 請求來發送

          if (ticket.IsPersistent)     //票證是否持久存儲
          {
              cookie.Expires = ticket.Expiration;
          }

          return cookie;
      }

三、站點2讀取cookie

       T user=null;

       if (HttpContext.User != null
          && HttpContext.User.Identity.IsAuthenticated
          && HttpContext.User.Identity.Name != string.Empty
          && HttpContext.User.Identity.AuthenticationType == "Forms")
          {
                 FormsIdentity id = HttpContext.User.Identity as FormsIdentity;

                 if (id != null)
                {
                      FormsAuthenticationTicket ticket = id.Ticket;

                      user = this.DeserializeUserInfo(ticket.UserData);

                      if (user == null)
                      {
                          return false;
                      }

                      return true;

                }
                else
                {
                     user = default(user);

                     return false;
                }
        }
        else
        {
             user = default(user);

             return false;
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM