我在ASP.NET应用程序中使用表单验证.我将FormsAuthenticationTicket配置为1年后到期,但实际在1小时左右后过期.我不知道为什么.
public static bool Login(int id) { try { string securityToken = UserHelper.AuthenticateUser(id); DateTime expiryDate = DateTime.Now.AddYears(1); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1,id.ToString(),DateTime.Now,expiryDate,true,securityToken,FormsAuthentication.FormsCookiePath); string encryptedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket); cookie.Expires = expiryDate; HttpContext.Current.Response.Cookies.Add(cookie); return true; } catch { return false; } }
Web.config文件:
<system.web> <machineKey validationKey="AutoGenerate" decryptionKey="AutoGenerate" validation="SHA1" /> <compilation debug="true"> <authentication mode="Forms"> <forms loginUrl="~/Login.aspx" timeout="2880"/> </authentication> ...
我的做法有问题吗?为什么它过期如此之快?
编辑
全球代码:
protected void Application_AuthenticateRequest(object sender,EventArgs e) { if (Request.PhysicalPath.EndsWith(".aspx") || Request.PhysicalPath.EndsWith(".axd") || Request.PhysicalPath.EndsWith(".ashx")) SecurityManager.SetPrincipal(); }
SetPrincipal代码:
public static void SetPrincipal() { ILivrePrincipal principal = null; FormsIdentity identity; UrlParameters urlParameters = UrlParametersHelper.GetUrlParameters(HttpContext.Current.Request); if (HttpContext.Current.Request.IsAuthenticated) { identity = (FormsIdentity)HttpContext.Current.User.Identity; User userProfile; urlParameters.SecurityToken = (((FormsIdentity)identity).Ticket).UserData; try { userProfile = UserHelper.GetUser(urlParameters.SecurityToken); UserHelper.UpdateLastActiveOn(userProfile); principal = new AuthenticatedPrincipal(identity,userProfile); } catch { //TODO: Log an exception FormsAuthentication.SignOut(); principal = new AnonymousPrincipal(new GuestIdentity(),UserHelper.GetUser(null)); } } else { principal = new AnonymousPrincipal(new GuestIdentity(),UserHelper.GetUser(null)); } HttpContext.Current.User = principal; }
解决方法
这是你的问题.
<machineKey validationKey="AutoGenerate" decryptionKey="AutoGenerate" validation="SHA1"/>
每当应用程序池循环使用时,ASP将会生成一个新的机器密钥.哪个时间可以合理地发生.
机器密钥用于加密和解密您的FormsAuthentication cookie.如果它更改,浏览器上的cookie不再是任何好的.所以系统会对待你,好像你从来没有登录过.
<machineKey validationKey="21F090935F6E49C2C797F69(snip)F1B72A7F0A281B" decryptionKey="ABAA84D7EC4BB56D75D(snip)B8BF91CFCD64568A145BE59719F" validation="SHA1" decryption="AES" />