【问题标题】:remember me(isPersistent) dont work on Forms authentication记住我(isPersistent)不适用于表单身份验证
【发布时间】:2015-01-19 19:40:38
【问题描述】:

这里是我的 cookie 创建代码: 这是控制器(model.RememberMe 是一个复选框值)

int timeout = (model.RememberMe) ? (int) FormsAuthentication.Timeout.TotalMinutes : Session.Timeout;//4h
                    HttpCookie cookie = accountService.GetCookie(userId, model.RememberMe, timeout);
                    Response.Cookies.Add(cookie);
                    Logger.Debug("POST: AccountController LogOn end.");
                    result = returnUrl != null
                        ? RedirectToLocal(returnUrl)
                        : RedirectToAction("Index", "Profile", new {id = userId});

创建 cookie 的服务方法

public HttpCookie GetCookie(int userId, bool rememberMe, int timeout)
        {
            Logger.Trace("AccountService GetCookie start with arguments:" +
                         " userId = {0}, rememberMe = {1}.", userId, rememberMe);
            var authTicket = new FormsAuthenticationTicket(
                               1,
                               Convert.ToString(userId),
                               DateTime.Now,
                               DateTime.Now.AddMinutes(timeout),
                               rememberMe,
                               string.Empty,
                               "/"
                               );
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                FormsAuthentication.Encrypt(authTicket));
            Logger.Debug("Cookie for user with userId = {0} has created", userId);
            Logger.Trace("AccountService GetCookie end.");
            return cookie;
        }

但不幸的是,RememberMe 不起作用,并且 cookie 在浏览器会话结束时过期。为什么?

What is the purpose of FormsAuthenticationTicket isPersistent property?这里有某种答案,但我不明白为什么它不起作用?

【问题讨论】:

    标签: asp.net asp.net-mvc cookies


    【解决方案1】:

    您的代码与您链接的 SO 答案之间的区别在于它们使用:

    FormsAuthentication.SetAuthCookie(model.UserName, true);

    这使得 cookie 基于IsPersistent 属性具有适当的过期时间。但是,如果您使用代码中的构造函数返回 cookie:

    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));

    然后过期时间将设置为浏览器会话,因为这是HttpCookie 类的默认行为:what is the default expiration time of a cookie

    所以你可能有两个选择。使用您链接到的答案中概述的FormsAuthentication.SetAuthCookie 方法,或添加:

    cookie.Expires = DateTime.Now.AddMinutes(10); // or whatever you want

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多