I have an AJAX method to call on server to return “.ASPXAUTH” cookie expiration time.
It works properly when the auth cookie presents.
Besides I want to renew user logon session with another AJAX call. I have a blank method “RenewSession” which is just for to make a call to the server. Is there any way to do this using Forms Authentication?
The problem is in that when I make a request to server to my “RenewSession” method to renew the session Response.Cookies array is always containing 0 items. But actually when the “.ASPXAUTH” cookie expiration time gets to 0 it renews.
So can anyone explain is it a browsers’ or ASP.NET/MVCs’ behaviour?
Maybe I need sliding expiration to be set to “true”?
Or maybe in my renew method I should re-login the user and put a new cookie in the response?
Thank you!
FormsAuthentication expiration is really a matter of two parts:
If you want to leave sliding expiration off, and renew the ticket manually, you need to renew the ticket and return a new authentication cookie to the browser.
The
Response.Cookiesarray is empty unless you (or other code) add something to it. It’s only meant for adding cookies that are new or whose contents/expiration/whatever have changed. An emptyResponse.Cookiesonly means that nothing has changed – the browser will keep the cookies it already has (until they expire) and still send them on the next request.The standard way of modifying cookie contents or expiration is to take a cookie the browser sent (from
Request.Cookies), modify it, and then add it toResponse.Cookies.Here’s a bit of sample code for manually renewing the authentication cookie (disclamer: Test thoroughly and think):
Note that
FormsAuthentication.RenewTicketIfOld()won’t always renew the ticket. It will only renew if less than half of the expiration time is left. I.e., if your timeout in web.config is set to 20 minutes and RenewTicketIfOld is called 7 minutes after the ticket was created, the ticket won’t be renewed, and there’ll still be 13 minutes left. If it’s called after e.g. 12 minutes, it will be renewed to 20 minutes.The reason for this is because RenewTicketIfOld is used by slidingExpiration on every request and so would send back a new cookie on every request (to reset the expiration to [timeout] minutes). Only sending a new ticket cookie back when at least half the time has elapsed gets rid of a lot of cookie overhead – at the expense of being confusing to developers and end users.
*) On
cookie.Secure, see Hanselman: Weird Timeouts – this simply makes sure that if RequireSSL is set in web.config, the cookie will honor that, which avoids many a debugging nightmare if you ever move the site to SSL.