FormsAuthenticationTicket學習筆記


自己的代碼,很亂給自己看 

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddDays(365),
             true, string.Format("{0}:{1}", "username", "password"), FormsAuthentication.FormsCookiePath);
            //這邊的 string.Format("{0}:{1}", "username", "password"),也可以改為任何值,如密碼或IP
            string ticString = FormsAuthentication.Encrypt(ticket);
            //將加密后的票據保存為cookie 
            HttpCookie coo = new HttpCookie(FormsAuthentication.FormsCookieName, ticString);
            //這里的IsPersistent不會自己判斷,需要手工判斷,但FormsAuthenticationTicket的expiration的值是有過期性的,無論cookie的Expires設置多久,只要expiration到期,即使cookie存在用戶驗證也將失敗
            if (ticket.IsPersistent)
            {
                coo.Expires = ticket.Expiration;
            }
            //使用加入了userdata的新cookie 
            Response.Cookies.Add(coo);
            //FormsAuthentication.SetAuthCookie("username", true);//這種是快速寫法,用了這種寫法就可以不用自己建ticket票據,也無法使用UserData等參數了


            //FormsAuthentication.SignOut//用來清除這個Cookie標記//FormsAuthentication.RedirectFromLoginPage(userID, createPersistentCookie);

        //    <authentication mode="Forms">
        //    <forms name=".MyCookie" loginUrl="Login.aspx" protection="All" timeout="60"/>
        //    </authentication> 

 

總結:

1.FormsAuthentication一共有兩種生成並記錄票具的方法:

  一種是自己new FormsAuthenticationTicket,然后自己保存到Cookie中,ticket的IsPersistent屬性僅起到標識的作用,並不會去修改Cookies的到期時間,需要人工自己判斷后設置cookies的到期時間(if (ticket.IsPersistent){coo.Expires = ticket.Expiration; })。

  另一種是使用FormsAuthentication.SetAuthCookie("username",IsPersistent: false);來快捷生成ticket,這種方法系統會自動新建一個cookies來保存ticket,並根據IsPersistent是否為true,以及webconfig中的timeout來確定cookies的到期時間。

2.如果使用第一種方法,無論自己把cookies的時間設置為多久,只要ticket.Expiration到期了,及時cookies還存在,用戶驗證依然會失敗。

3.UserData是個好東西,可以用來存儲IP地址,用於判斷訪問者是否是惡意截取cookies。

推薦一篇好文:http://www.cnblogs.com/zxjyuan/archive/2009/08/21/1551196.html


免責聲明!

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



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