防止 FormsAuthentication 過期時間增加
我有一個使用表單身份驗證的相對簡單的基於 WebForms 的站點:
<authentication mode="Forms"> <forms loginUrl="login.aspx" defaultUrl="secure/home.aspx" name=".AdminSite" /> </authentication>由於沒有明確提及,
slidingExpiration預設情況下設置為 true,因此只要使用者仍在站點中導航,他們就不會註銷。但是,我希望特定頁面不增加到期時間。這可能是
web.config在程式碼內部還是程式碼中?我看到的唯一建議提到設置slidingExpiration為false,這將適用於側面。身份驗證 cookie 使用以下方式設置:
FormsAuthentication.RedirectFromLoginPage(username, False)因此更改身份驗證 cookie 本身是不切實際的。
滑動過期是由
FormsAuthentication模組在必要時通過重新發布 cookie 來實現的。為防止滑動,您需要防止 cookie 更新發生。這可以通過簡單地
FormsAuthentication從響應中刪除 cookie 來完成。下面是一個非常簡單的 Web 表單背後的程式碼。該
aspx頁面有一個div顯示Page_Load事件的輸出。public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { testDiv.InnerHtml = "Hi, cookie is: " + HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value; testDiv.InnerHtml += "<br />"; var ticket = FormsAuthentication.Decrypt( HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value); testDiv.InnerHtml += "Expires: " + ticket.Expiration.ToString("yyyy-MM-dd HH:mm:ss"); if(Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) testDiv.InnerHtml += "<br />Forms auth is trying to update the cookie in this response"; } protected void Page_Prerender(object sender, EventArgs e) { if (Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) Response.Cookies.Remove(FormsAuthentication.FormsCookieName); } }如果 cookie 存在,該
Page_Prerender事件會從響應中刪除FormsAuthentication它,從而防止滑動。我通過將超時設置為
FormsAuthentication兩分鐘來測試這一點。然後我開始調試並登錄。然後我不斷刷新有問題的頁面。由於
FormsAuthentication除非過期時間已經過去一半,否則不會更新 cookie,所以在第一分鐘,頁面將繼續顯示相同的加密 cookie 和相同的過期時間。一分鐘多一點後,頁面將報告FormsAuthentication正在嘗試更新 cookie。但是Page_Prerender刪除了cookie,因此它不會被發送。再過一分鐘,您將被重定向到登錄頁面。測試相同但刪除該
Page_Prerender方法表明 cookie 已更改,並且過期時間會在大約一分鐘後更新。