Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to LogIn page when Session is expired (ASP.NET 3.5 FormsAuthen)

Tags:

asp.net

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);                                           

            }
        }
like image 219
Thurein Avatar asked Mar 17 '09 12:03

Thurein


1 Answers

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.

like image 197
Pawel Krakowiak Avatar answered Oct 05 '22 05:10

Pawel Krakowiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!