I'm using FormsAuthentication and ASP.Net SqlMembership Provider. I would like to provide a functionality to redirect to LogIn page when the underlying Session is expired.
I put the following block of codes in my BasePage OnInit. As far as I tested, it always keeps on redirecting to LogIn page even though I supplied correct UserID and Password. By rights, it should take me to default page.
if (Context.Session != null && Session.IsNewSession && this.Request.IsAuthenticated)
{
string cookieHeader = Request.Headers["Cookie"];
if (cookieHeader != null && cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
{
HttpContext.Current.Session.Abandon();
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.LoginUrl);
}
}
You don't need any custom code for this functionality, it's supported by the Framework. Just configure it in the web.config:
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx"
loginUrl="~/Login.aspx"
slidingExpiration="true"
timeout="60" />
</authentication>
With the configuration above, the user will be always redirected to the Login.aspx page when their session expires. There is a timeout of 60 minutes, and sliding expiration means that the timeout is extended each time the user makes a request to the web application, so if he stays active the session will not expire. A configuration like this gives you another advantage over what you tried to do - once the user logs in he will be automatically redirected back to the resource he originally requested. And you can always override and customize this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With