我有这个应用程序使用自定义方法使用FormsAuthentication注册和登录用户。托管此服务器的服务器具有每15分钟重新启动一次会话的策略,当发生这种情况时,我的所有用户都会被注销。登录用户的代码是:
var user = this.accountRepo.GetUser(id);
// Create the forms authentication cookie
var cookieValue = user.name;
HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieValue, true);
// Dercrypt the cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
// Create a new ticket with the desired data
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket
(
ticket.Version,
ticket.Name,
ticket.IssueDate,
DateTime.Now.AddYears(1),
true,
user.Authentication
);
// Update the cookies value
cookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Set(cookie);
accountRepo.Login(user);
创建Forms cookie并使用我的身份验证数据(基本上是用户哈希密码),然后使用以下逻辑显示Login按钮或用户名:
@{
var accountRepo = new AccountRepository();
var user = accountRepo.GetCurrentUser();
}
@if(user != null && user.LoggedIn) {
<div>@Html.ActionLink(Context.User.Identity.Name + " - Logout", "LogOff", "Account", null, new { @class = "logout_link" })</div>
}
else
{
@Html.ActionLink("Login", "Login", "Account", new { returnUrl = Request.Url.AbsoluteUri }, new { @class = "login_link" })
}
并且“GetCurrentUser()”方法是:
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
return db.Users.SingleOrDefault(u => u.Authentications.Equals(ticket.UserData, StringComparison.CurrentCultureIgnoreCase));
}
return null;
我在这里遗漏了什么吗?我相信使用此代码如果会话重新启动,我的用户应该保持登录状态。
提前致谢。
答案 0 :(得分:0)
正如Mystere Man所说的那样。每次会话重新启动时都会重新生成cookie名称,因此应用程序正在查找名称与之前名称不同的cookie。
为了让所有帮助我的人以及将来支持这个应用程序的开发人员高枕无忧,我重新构建了它,而不再是“邪恶”:P