我在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; } }
<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" />
原文地址:https://www.jb51.cc/csharp/93505.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。