记住我在ASP.NET表单身份validation中的function不起作用
我正在使用ASP.NET表单身份validation将用户登录到我们正在开发的网站中。
部分function是“记住我”复选框,如果用户检查,则会记住用户一个月。
用户登录的代码如下:
public static void Login(HttpResponse response, string username, bool rememberMeChecked) { FormsAuthentication.Initialize(); FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), rememberMeChecked, FormsAuthentication.FormsCookiePath); HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt)); ck.Path = FormsAuthentication.FormsCookiePath; if (rememberMe) ck.Expires = DateTime.Now.AddMonths(1); response.Cookies.Add(ck); }
web.config中的相关部分是这样的:
这会记录用户正常但如果他们不使用该站点,则在半小时后将其记录下来,尽管其持久性属性(rememberMeChecked)设置为true,如果为true,则cookie设置为在一个月后过期。 这里有什么我想念的吗?
在此先感谢,F
您的身份validation票证仍然配置为在半小时后过期,即使Cookie本身在30天后到期。 您可能还需要延长票证的生命周期:
public static void Login(HttpResponse response, string username, bool rememberMeChecked) { DateTime expiration = DateTime.Now.AddMinutes(30); if (rememberMe) { expiration = DateTime.Now.AddMonths(1); } FormsAuthentication.Initialize(); FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, DateTime.Now, expiration, rememberMeChecked, FormsAuthentication.FormsCookiePath); HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt)); ck.Path = FormsAuthentication.FormsCookiePath; response.Cookies.Add(ck); }
尝试在web.config中设置forms标签的Name属性
此外, Firecookie在调试这些问题时非常棒
只需再次阅读您的代码,您还在票证构造函数中指定了DateTime.Now.AddMinutes(30)
…必须检查是否会影响它
在我看来,你正在检查“rememberMe”而不是你传递的名为“rememberMeChecked”的变量。
您已在FormsAuthenticationTicket
的构造函数中指定了DateTime.Now.AddMinutes(30)
。 这是设置登录到期的原因。
我意识到必须更新身份validation票证,而不仅仅是阅读。 我的Application_BeginRequest方法现在看起来像这样:
if (!Request.IsAuthenticated) { HttpCookie ck = Request.Cookies[FormsAuthentication.FormsCookieName]; if (ck != null) { FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(ck.Value); UserManagementUtils.RenewFormsAuthenticationTicket(Response, oldTicket); } }
这似乎照顾了它。