FormsAuthenticationTicket:关闭浏览器后如何保持用户登录?

时间:2018-07-31 08:13:19

标签: .net asp.net-mvc authentication

我正在使用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年),当我关闭浏览器并重新打开网站时,也会注销用户。

关闭浏览器后如何保持登录状态?

1 个答案:

答案 0 :(得分: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;
}
...