gpt4 book ai didi

.net - 表单例份验证票 : how to keep the user logged in after the browser has been closed?

转载 作者:行者123 更新时间:2023-12-02 15:27:07 25 4
gpt4 key购买 nike

我使用 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;
}
...

关于.net - 表单例份验证票 : how to keep the user logged in after the browser has been closed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51608529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com