Asp.net

防止 FormsAuthentication 過期時間增加

  • November 18, 2015

我有一個使用表單身份驗證的相對簡單的基於 WebForms 的站點:

<authentication mode="Forms">
 <forms loginUrl="login.aspx" defaultUrl="secure/home.aspx" name=".AdminSite" />
</authentication>

由於沒有明確提及,slidingExpiration預設情況下設置為 true,因此只要使用者仍在站點中導航,他們就不會註銷。

但是,我希望特定頁面增加到期時間。這可能是web.config在程式碼內部還是程式碼中?我看到的唯一建議提到設置slidingExpirationfalse,這將適用於側面。

身份驗證 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 已更改,並且過期時間會在大約一分鐘後更新。

引用自:https://stackoverflow.com/questions/33632509