1、登錄添加:
ticket = new FormsAuthenticationTicket(
1,
us.RealName,
DateTime.Now,
DateTime.Now.AddMinutes(1),
true, //票據是否持久性,若為false,設定時間到后票據過期,若為true,票據持久有效,設定時間無效。當設定為true時只是票據持久,但cookie並不是持久,還有根據需要設定cookie的Expires
us.Roles,
"/"
);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.HttpOnly = true;
HttpContext.Response.Cookies.Add(cookie);
2、配置文件
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="~/Users/Login" defaultUrl="~/Home/Index" protection="All" timeout="30" path="/" requireSSL="false" slidingExpiration="true" enableCrossAppRedirects="false" cookieless="UseDeviceProfile" domain="" />
</authentication>
slidingExpiration="true"時,在瀏覽器不超過timeout="30"設定的時間時,將重新更新cookie過期時間,也就是在這個時間內沒有訪問服務器,那么cookie會過期,若有訪問服務器,那么cookie期限將從新設為這個時間。
3、以上兩條,第一條,票據是持久的,第二條,cookie是滑動的,配合實現很好的登錄時效性控制。