c# – 为什么我的表单认证票证过期如此之快?
发布时间:2020-12-15 03:53:15 所属栏目:百科 来源:网络整理
导读:我在ASP.NET应用程序中使用表单验证.我将FormsAuthenticationTicket配置为1年后到期,但实际在1小时左右后过期.我不知道为什么. 以下是登录过程中涉及的所有代码: public static bool Login(int id){ try { string securityToken = UserHelper.AuthenticateU
我在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" /> 生成一个关键here. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |