【问题标题】:ASP.MVC Remember me cookie not working after session time outASP.MVC 记住我 cookie 在会话超时后不起作用
【发布时间】:2014-12-23 08:54:58
【问题描述】:

在登录表单上,我有一个选项允许用户单击“记住我”复选框,该复选框会创建一个新的FormsAuthenticationTicket,然后将其添加到 cookie 中。

if (_model.RememberMe)
{

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                      _model.Username,
                                      DateTime.Now,
                                      DateTime.Now.AddDays(30),
                                      true,
                                      _model.Username,
                                      FormsAuthentication.FormsCookiePath);

    // Encrypt the ticket.
    string encTicket = FormsAuthentication.Encrypt(ticket);

    // Create the cookie.
    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

如上所述,它应该在客户端浏览器中保留 30 天。

对此进行测试,我故意将当前会话超时仅保留一分钟

<sessionState timeout="1"></sessionState>

所以一分钟后,如果用户说“记住我”,我希望网站不应该被重定向回登录页面。然而它确实如此。这是执行此操作的代码。

        // [".ASPXAUTH"] is the cookie name that is created by the FormsAuthenticationTicket`
        if (User.Identity.Name == "" && Request.Cookies[".ASPXAUTH"] == null)
        {

            return RedirectToAction("LogOut", "Login");
        }


        // the current session hasn't timed out or the remember me cookie is enabled
        FormsIdentity id = (FormsIdentity)User.Identity;
        FormsAuthenticationTicket ticket = id.Ticket;

但是 cookie 是 NULL。

我认为这是对我的误解,所以如果有人可以帮帮我。我会很感激。

谢谢

【问题讨论】:

  • 您为什么手动执行此操作而不使用FormsAuthentication.SignIn
  • 因为直到现在我才听说过这个lol
  • 而 .NET 4.5 没有 FormsAuthentication.SignIn 可能已经过时了
  • 那你为什么不阅读一些关于如何以正确方式实现它的教程呢? asp.net/mvc 有一些不错的

标签: c# asp.net-mvc cookies forms-authentication formsauthenticationticket


【解决方案1】:

你要找的是

string mySessionCookie = System.Web.HttpContext.Current.Request.Headers["Cookie"];
if (mySessionCookie.IndexOf(".ASPXAUTH", StringComparison.Ordinal) >= 0) {
    // do something
}

编辑

这个怎么样,我没有测试过,但我记得以前做过类似的事情

HttpCookie cookie = (HttpCookie)(Request.Cookies[FormsAuthentication.FormsCookieName]);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

【讨论】:

  • 感谢它有效,但是我无法通过这种方式从 cookie 访问用户名
  • 我提出了一种不同的方法,但我必须说 Request.Cookies[".ASPXAUTH"] 适合我。
  • @user3428422 如果这回答了您的问题,您能否将其标记为已回答。谢谢。
  • 不记得了 - 我不这么认为,因为我通常会立即标记,我会在今天的某个时候复习
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 2014-12-05
  • 2018-03-01
相关资源
最近更新 更多