我使用asp.net mvc與asp.net成員資格。
我想要一個複選框,如果點擊可以讓用戶登錄2周(除非他們清除了cookie)。
所以我知道他們是
FormsAuthentication.SetAuthCookie(用戶名,createPersistentCookie)
,但我不知道如何將其設置爲2周保留。
我重寫了大部分的會員資料。所以我不使用Create()和VerifyUser()之類的東西。
我使用asp.net mvc與asp.net成員資格。
我想要一個複選框,如果點擊可以讓用戶登錄2周(除非他們清除了cookie)。
所以我知道他們是
FormsAuthentication.SetAuthCookie(用戶名,createPersistentCookie)
,但我不知道如何將其設置爲2周保留。
我重寫了大部分的會員資料。所以我不使用Create()和VerifyUser()之類的東西。
您可以在web.config中設置全局會話超時(以分鐘爲單位)例如。
<system.web>
<authentication mode="Forms">
<forms timeout="20160"/>
</authentication>
</system.web>
這將適用於所有通過身份驗證的用戶。如果你想使用'記住我'功能,那麼你將需要編寫自己的代碼來設置cookie/ticket。像這樣的東西(採取from here):
protected void Page_Load()
{
if (Request.Cookies["username"] == null || Request.Cookies["username"].Value.ToString().Trim() == "")
{
Login1.RememberMeSet = true;
}
else
{
Login1.UserName = Request.Cookies["username"].Value.ToString().Trim();
Login1.RememberMeSet = true;
}
}
protected void RememberUserLogin()
{
// Check the remember option for login
if (Login1.RememberMeSet == true)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Value = Login1.UserName.Trim();
cookie.Expires = DateTime.Now.AddHours(2);
HttpContext.Current.Response.AppendCookie(cookie);
Login1.RememberMeSet = true;
}
else if (Login1.RememberMeSet == false)
{
HttpContext.Current.Response.Cookies.Remove("username");
Response.Cookies["username"].Expires = DateTime.Now;
Login1.RememberMeSet = false;
}
}
向cookie和數據庫(都是同一個鍵)添加散列鍵或隨機字符串。如果cookie和數據庫值相同,則當用戶開始新會話時,請再次簽署他/她。當用戶達到兩週時間時,使用cronjob(Unix)或計劃任務(Windows)從數據庫中刪除密鑰。
警告:不要依賴cookie過期日期,因爲人們可以破解他們的瀏覽器。
規則:永遠不要相信你的任何用戶!
你能解釋一下隨機字符串的哈希如何提高你的解決方案的安全性嗎?如果隨機字符串的散列值存儲在數據庫和cookie中,那麼這與將數據庫和cookie中的隨機字符串存儲的本質不同? – rinogo 2010-12-10 22:05:28
我使用散列鍵和隨機字符串的同義詞。 – 2010-12-10 23:43:18
只需使用2周到期日期的簡單餅乾即可。
迄今爲止最簡單的方法 - 也是最簡單的方法。 – 2009-08-19 16:24:10
小問題,但如果設置了到期日期,它不是「會話」cookie。這是一個「永久」cookie。 – MrWhite 2014-05-22 15:25:21
@ w3d同意。更正了 – 2014-05-23 12:02:53
你有沒有考慮過將答案標記爲已接受的答案? – 2009-08-19 16:16:42