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);
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
Pawel’s answer is partially correct, but you also need to set the Session lifetime to a value longer than the forms authentication cookie lifetime as well. The forms authentication timeout value only affects the lifetime of the authentication cookie. In the example he provided, the authentication cookie lifetime is 60 minutes but the default session lifetime is 20 minutes. If a user left their machine for more than 20 minutes their session data would be discarded, subsequent attempts to reference a value stored in session would result in an exception being thrown (for example System.NullReferenceException if attempting to .ToString() or a cast).
You can set this globally in your application by configuring the sessionState settings in your web.config file:
<sessionState
mode="InProc"
cookieless="false"
timeout="70"/>
Adding five or ten minutes to the session timeout provides a good buffer.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0