.net – FormsAuthenticationTicket:如何在浏览器关闭后让用户保持登录状态?

我使用FormsAuthenticationTicket以这种方式记录用户:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel loginView)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(loginView.Email, loginView.Password))
        {
            var user = (CustomMembershipUser)Membership.GetUser(loginView.Email, false);
            if (user != null)
            {
                CustomPrincipalSerializeModel userSerializeModel = new CustomPrincipalSerializeModel()
                {
                    ID = user.ID,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    RoleName = user.Roles.Select(r => r.RoleName).ToList()
                };

                string userData = JsonConvert.SerializeObject(userSerializeModel);
                DateTime expirationDate = loginView.KeepMeLoggedIn ? DateTime.Now.AddMonths(12) : DateTime.Now.AddMinutes(15);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, expirationDate, false, userData);

                HttpCookie faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket));
                Response.Cookies.Add(faCookie);
            }

            return RedirectToAction("Index", "Home");
        }
    }

    ModelState.AddModelError("", "Login Error");

    return View("Login");
}

但即使我将loginView.KeepMeLoggedIn设置为true(应保持登录1年),当我关闭浏览器并重新打开网站时,用户将被注销.

当我关闭浏览器时,如何保持登录状态?

最佳答案 首先,您需要将FormsAuthenticationTicket构造函数’isPersistent’的第5个参数设置为true.

然后我会添加更改代码到这个:

var faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent)
{
    faCookie.Expires = authTicket.Expiration;
}
Response.Cookies.Add(faCookie);

如果您还想要尊重web.config中配置的内容,您可以添加此额外代码(可选):

var faCookie= new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
faCookie.Path = FormsAuthentication.FormsCookiePath;

if (FormsAuthentication.RequireSSL)
{
    faCookie.Secure = true;
}

if (FormsAuthentication.CookieDomain != null)
{
    faCookie.Domain = FormsAuthentication.CookieDomain;
}
...
点赞