FormsAuthenticationTicket expires too soon

百般思念 提交于 2019-12-05 04:08:33
6opuc

It may happen because of Application Pool recycling.

Authentication cookie is encrypted with machine keys. It seems that by default these machine keys are generated at each application pool restart. Then your application is idle for some time(configured in application pool settings) your application pool is recycled.

So you need to generate static machine keys.

This question is related to yours: Can a FormsAuthenticationTicket survive an app pool recycle?

Have you looked at modifying the timeout in the web.config file?

<forms 
   name="name" 
   loginUrl="URL" 
   defaultUrl="URL"
   protection="[All|None|Encryption|Validation]"
   timeout="[MM]"
   path="path"
   requireSSL="[true|false]"
   slidingExpiration="[true|false]">
   enableCrossAppRedirects="[true|false]"
   cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]" 
   domain="domain name"
   ticketCompatibilityMode="[Framework20|Framework40]">
   <credentials>...</credentials>
</forms>

I've used this snippet and it works for me, take a look at this:

        FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket( 
                                              1,                                        // Ticket version
                                               username,                                 // Username associated with ticket
                                               DateTime.Now,                             // Date/time issued
                                               DateTime.Now.AddDays(1),                 // Date/time to expire
                                               isPersistent,                             // "true" for a persistent user cookie
                                               dataStore,                                // User-data, in this case the roles
                                               FormsAuthentication.FormsCookiePath);     // Path cookie valid for

        // Encrypt the cookie using the machine key for secure transport
        string Hash = FormsAuthentication.Encrypt(Ticket);
        HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, Hash);

        // Set the cookie's expiration time to the tickets expiration time
        if (Ticket.IsPersistent)
            Cookie.Expires = Ticket.Expiration;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!