我正在构建一个 Web 应用程序(框架 4.6),并且正在使用 FormsAuthentication 来管理安全性。
目前,它允许用户登录/注销等......一切都很好。但是,我想定期检查 Forms Authentication Ticket 的到期时间,并弹出一个对话框,其中包含用户将按下以延长时间的按钮。所以我基本上让它工作了,除了当票被更新时,用户基本上被踢出去了,我不知道为什么。
这是登录代码:
FormsAuthenticationTicket faTicket = new FormsAuthenticationTicket(1, user.UserID, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), persistLogin, "");
string cookiestr = FormsAuthentication.Encrypt(faTicket);
HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (persistLogin)
ck.Expires = faTicket.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
HttpContext.Current.Response.Cookies.Add(ck);
这是机票续订代码:
FormsIdentity identity = ((FormsIdentity)HttpContext.Current.User.Identity);
string userID = identity.Name;
HttpCookie cookie = FormsAuthentication.GetAuthCookie(userID, true);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
ticket.Version,
userID,
ticket.IssueDate,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes),
ticket.IsPersistent,
ticket.UserData,
ticket.CookiePath);
cookie.Value = FormsAuthentication.Encrypt(newTicket);
if (ticket.IsPersistent)
cookie.Expires = newTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);
顺便说一句,我处理剩余时间的方式如下(在 ashx 处理程序文件中):
FormsIdentity identity = ((FormsIdentity)HttpContext.Current.User.Identity);
DateTime expires = identity.Ticket.Expiration;
// offset the expiry time by a few seconds, because otherwise the FormsAuthentication will prevent this Handler from executing
expires = expires.AddSeconds(-5);
TimeSpan ts = expires - DateTime.Now;
double mins = ts.Minutes;
double secs = ts.Seconds;
string countdownText = mins.ToString().PadLeft(2, '0') + ":" + secs.ToString().PadLeft(2, '0');