Forms authentication is nice way to protect your asp.net web pages from unauthorized views. The good thing is that it shields all request for pages in your site and will redirect the request to a login page. You can set the time out of a session, after a preset period of inactivity the user has to be re-authenticated.
Al done in the web.config
<authentication mode="Forms"> <forms loginUrl="~/login.aspx" timeout="2"> </forms> </authentication> <authorization> <deny users="?"/> </authorization>
The bad thing is that forms authentication does not work that well with an AJAX site. When a partial postback hits the server and the session has timed out the server will redirect the request to the login page. This is a response the AJAX request cannot handle well. The result will be an endless loop of requests and the page just hangs. Damit Dobric has a very informative post on this. The good thing about Firefox is that it does detect the redirect loop and will stop. IE just keeps on trying.
Damir presents a solution for the problem which does requires quite some fiddling. Here I would like to present a simpler solution.
The page load of the masterpage checks if the request is the first one in the current session by inspecting the Session.IsNewSession property. In a page shielded with forms authentication this will never be the case; posting back the login form was the first request. But when the request was issued by a partial postback in a timed out session the IsNewSession property will read true and the situation can be handled.
protected void Page_Load(object sender, EventArgs e)
{
// Ajax postback, session timed out. Redirect
if (Session.IsNewSession)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Default.aspx", true);
}
}
It explicitly signs out of FormAuthentication and redirects the user to the main page. No more loops, no more hangups.