一、先看一下使用FormsAuthentication做登錄認證的用法
用法一:
FormsAuthentication.SetAuthCookie(username, isPersistent);
用法二:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(720), isPersistent, userData, FormsAuthentication.FormsCookiePath); // 加密票證 string encTicket = FormsAuthentication.Encrypt(ticket); // 創建cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); HttpContext.Current.Response.Cookies.Add(cookie);
二、幾個問題
1.用法一和用法二區別?
2.用法一中的認證過期時間是如何設置的?用法二中又是如何設置的?
3.用法二中票證中設置過期時間和Web.config中設置的過期時間哪個優先?
4.用法二中userData是否可以為null?
5.用法中的isPersistent是什么?
6.什么是持久化cookie?什么是會話性cookie?
7.用法二中的isPersistent為何沒起作用?
三、解答
1.用法一無法使用userData數據。
2.用法一中的過期時間為Web.config中配置的時間。
3.用法二中票證中設置的過期時間優先於Web.config中設置的過期時間(即以票證中設置的過期時間為准)。
4.用法二中userData不可為null,否則無法加密票證。詳見MSDN文檔。
5.isPersistent表示是否要持久化認證cookie。
6.持久化cookie保存在物理介質中。(win7中的位置為C:\Users\用戶名\AppData\Roaming\Microsoft\Windows\Cookies,注意Appdata是個隱藏的文件夾)
會話性cookie保存於內存中。關閉瀏覽器則會話性cookie會過期消失;持久化cookie則不會,直至過期時間已到或確認注銷。
注意:如果要使用會話性cookie,就不能為cookie對象設置過期時間,一旦設置了過期時間就為持久化cookie。
7.其實用法二是大家常見的寫法,但這種寫法並沒有使isPersistent。參考以下寫法:
public static void SetFormsAuthentication(string username, bool isPersistent, string userData) { userData = string.IsNullOrEmpty(userData) ? string.Empty : userData; //創建票證 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(720), isPersistent, userData, FormsAuthentication.FormsCookiePath); // 加密票證 string encTicket = FormsAuthentication.Encrypt(ticket); // 創建cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { HttpOnly = true, Path = FormsAuthentication.FormsCookiePath, Secure = false }; if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } HttpContext.Current.Response.Cookies.Add(cookie); }