Asp.net

asp.net cookie、身份驗證和會話超時

  • January 18, 2009

我有一個使用表單身份驗證的 asp.net 網站。我在會話中保留了一些內容,例如使用者名、使用者 ID、電子郵件等。

我允許使用者通過在身份驗證 cookie 上設置較長的過期日期來保持登錄到網站。因此,會話在使用者仍然通過身份驗證時到期是很常見的。

我遇到的問題是有時使用者的會話超時但他們仍然經過身份驗證。因此,例如,我的一個使用者頁面(需要身份驗證)在會話處於活動狀態時會說“Welcome Mike”,但一旦過期,它會說“Welcome [blank]”,因為該資訊不再在會話中,但他們仍然經過身份驗證。

處理這個問題的最佳方法是什麼?當資訊不再存在時,我應該重新同步會話資訊嗎?或者我應該將使用者資訊(使用者名、使用者 ID、電子郵件)移動到 cookie 中,而不用擔心會話超時?

我不想將會話長度設置為 60 分鐘或更長。我想要的是讓我的使用者能夠登錄一次,而不必擔心在他們明確註銷之前必須再次登錄。

盡可能避免使用會話,如果你可以在沒有看到的情況下逃脫,它會使多伺服器部署變得更容易一些。可能,姓名和電子郵件很容易成為 cookie 的候選者。偽造 cookie 很容易,因此根據您的安全需求,使用者 ID 可能不是一個好主意。

表單身份驗證 cookie 已加密,您可以向這些 cookie 添加額外數據(請參閱下面的詳細資訊)。它可能是可破解的,但不像簡單的 cookie 那樣容易。

這是我過去使用的程式碼,稍作修改以刪除一些項目特定的細節。在登錄控制項的 LoggedIn 事件中呼叫它。

void AddUserIDToAuthCookie(string userID)  
{  
 //There is no way to directly set the userdata portion of a FormAuthenticationTicket  
 //without re-writing the login portion of the Login control  
 //  
 //I find it easier to pull the cookie that the Login control inserted out  
 //and create a new cookie with the userdata set  

 HttpCookie authCookie = Response.Cookies[AUTH_COOKIE];
 if(authCookie == null)
 {
   return;
 }

 Response.Cookies.Remove(AUTH_COOKIE);

 FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
 var newTicket =
   new FormsAuthenticationTicket(oldTicket.Version, oldTicket.Name, oldTicket.IssueDate, oldTicket.Expiration,
                                 oldTicket.IsPersistent, userID, oldTicket.CookiePath);

 authCookie.Value = FormsAuthentication.Encrypt(newTicket);

 Response.Cookies.Add(authCookie);
}

僅供參考,我從一個舊項目中複製了它並在此處對其進行了編輯以刪除一些項目特定的位,因此它可能無法編譯,但它會非常接近。

要在您的網頁中獲取 ID…

FormsAuthenticationTicket ticket = ((FormsIdentity) Page.User.Identity).Ticket;
string id = ticket.UserData;

我使用這種機制來儲存不屬於 aspnetdb 使用者數據的 id。如果您的所有身份數據都由 aspnetdb 處理,您可能只需要訪問 Page.User.Identity 對象。

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