【问题标题】:Why my users get logged out when the session gets restarted?为什么会话重新启动时我的用户会退出?
【发布时间】:2011-10-22 01:43:08
【问题描述】:

我有这个应用程序,它使用自定义方法使用 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);

使用创建的表单 cookie 和我的身份验证数据(基本上是用户哈希密码),然后我使用以下逻辑来显示登录按钮或用户名:

@{
    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;

我在这里遗漏了什么吗?我相信使用这段代码如果会话重新启动应该很重要,我的用户应该保持登录状态。

提前致谢。

【问题讨论】:

  • 哇,这里错得太多了,我什至不知道从哪里开始。在您的视图中实例化存储库???啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊您的问题是会话丢失时 cookiename 会更改,并生成新会话。将用户密码存储在 cookie 中,即使加密和散列也是一个坏坏坏主意。
  • 告诉我吧,一直是我和服务器的斗争
  • 不可怕,这是一小段代码,你应该可以重构。如果您需要重构方面的帮助,请发布其他问题。这对可能需要维护或只是阅读本文的人不公平。
  • @Mystere Man 为什么在视图中实例化存储库如此错误?

标签: c# .net asp.net-mvc-3 session


【解决方案1】:

正如神秘人所说。每次会话重新启动时都会重新生成 cookie 名称,因此应用程序正在寻找名称与之前不同的 cookie。

为了让所有帮助过我的人高枕无忧,也为了将来支持这个应用程序的开发者,我对其进行了重构,使其不再那么“邪恶”:P

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-22
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2014-12-15
    • 2011-09-12
    相关资源
    最近更新 更多