locked
Redirect to login page when session expires RRS feed

  • Question

  • User1347670962 posted

    I want to redirect to login page from other page after session ends, without doing refresh.

     I tried out doing

    System.Web.Security.FormsAuthentication.SignOut();

    System.Web.Security.FormsAuthentication.RedirectToLoginPage(); in Session_end of global.asax. Giving me the problem of "Object reference not set to instance"

    suggest me the solution.

    Regards,

    Shirish .M

     

    Friday, May 4, 2012 3:18 AM

Answers

  • User143067745 posted

    You mean to say that :

    You logged into your site and visit some page for eample: xyz.aspx. And now you left you system idle for a long time. Then it should automatically redirect to login page as the session time out occurs.

    As i gave you the solution:

     Let that your session expires in 5 minutes.

    Means you set your application code to expire session in 5 minutes.

    You can do this in WEB.CONF's form tag.This code will expire session in the server side.

    It will ensure that only active session user can access your pages.

                                       Now imagine you logged in and opened a page and left it for 10mins. Your session expired in 5 mins at server but at clinet side in your browser you are still in that page you have opened.

    Ok.

    Now put that code in your aspx page.As I told you it will refresh your page in 325 seconds means 5mins and 25 seconds.

    Let your session has been expired in 5 mins. but after 5 mins and 25 seconds when this will be refreshed it will go to server for current page.

    But since session has been expired server will not allow to access the page will ask for login again.

    Put in aspx page:

    <META HTTP-EQUIV="Refresh" CONTENT="325;URL=../Login.aspx"> .

    Put in web.conf: under <System.Web>

    <authentication mode="Forms">
                
    <forms cookieless="AutoDetect" defaultUrl="Your Defaul page" loginUrl="Your Login Page" enableCrossAppRedirects="false" name="Cookie Name" protection="All" requireSSL="false" timeout="5" slidingExpiration="true"/>
            </authentication>
            <!-- Authorization-->
            <authorization>
                <allow users="*"/>
            </authorization>

    Put Followin code in MasterPage's Load event(If you don't have master page put in every page load event excepting login page):

    protected void Page_Load(object sender, EventArgs e)
        {
          /* try
            {
                String str=Session.Contents["UserName"].ToString();
               
            }
            catch (Exception exx)
            {
                Response.Redirect("~/Login.aspx");
            }
           
            */
           if (Request.IsAuthenticated)
            {
                Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetNoStore();               
               
            }
            else
            {
                FormsAuthentication.RedirectToLoginPage();
               // Response.Redirect("~/Login.aspx");
            }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2012 4:13 AM
  • User-1199946673 posted

    I dont want to refresh or set the timer in javascript. I want to redirect to Login page when session timeout.

    Did it occur to you that what you ask is not possible? The web is stateless, Session timeout is an evenet that occurs on the webserver, not on the client!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 10, 2012 5:54 AM

All replies

  • User-2063567145 posted

    can you post code of your Global.asax file

    Friday, May 4, 2012 3:20 AM
  • User1347670962 posted

    using System;
    using System.Web;
    
    namespace WEI.ECommerce.Web
    {
        public class Global : System.Web.HttpApplication
        {
    
            void Application_Start(object sender, EventArgs e)
            {
                // Code that runs on application startup
    
            }
    
            void Application_End(object sender, EventArgs e)
            {
                //  Code that runs on application shutdown
    
            }
    
            void Application_Error(object sender, EventArgs e)
            {
                // Code that runs when an unhandled error occurs
    
            }
    
            void Session_Start(object sender, EventArgs e)
            {
                // Administrator will only be allowed a certain number of login attempts
                Session["MaxLoginAttempts"] = 3;
                Session["LoginCount"] = 0;
    
                // Track whether they're logged in or not
                Session["LoggedIn"] = "No";
    
                // Track whether Admin logged in or not
                Session["AdminLoggedIn"] = "No";
    
                //if (Session.Keys.Count > 0)
                //{
                //    System.Web.Security.FormsAuthentication.SignOut();
                //    System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                //}
                
            }
    
            void Session_End(object sender, EventArgs e)
            {
                // Code that runs when a session ends. 
                // Note: The Session_End event is raised only when the sessionstate mode
                // is set to InProc in the Web.config file. If session mode is set to StateServer 
                // or SQLServer, the event is not raised.
                System.Web.Security.FormsAuthentication.SignOut();
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                  
            }
    
            public override string GetVaryByCustomString(HttpContext context, string arg)
            {
                if (arg.ToLower() == "culture")
                {
                    if (context.Session["CultureName"] != null)
                        return context.Session["CultureName"].ToString();
                }
                return base.GetVaryByCustomString(context, arg);
            }
        }
    }
    

    Friday, May 4, 2012 3:27 AM
  • User-1199946673 posted

     I tried out doing

    System.Web.Security.FormsAuthentication.SignOut();

    System.Web.Security.FormsAuthentication.RedirectToLoginPage(); in Session_end of global.asax. Giving me the problem of "Object reference not set to instance"

    First of all, Forms authentication has nothing to do with Session! Forms authentication uses cookies, not session

    Session_end in Global.asax is not attached to any Request, it is a process that runs on the server, even when the user already closed his browser of is disconnected, so you cannot access the authentication cookie, resulting in this error

    Friday, May 4, 2012 4:35 AM
  • User1347670962 posted

    Thanks for your information . But my questioned need to be answered . I want to redirect to login page after session expires without refreshing the page.

    Friday, May 4, 2012 5:11 AM
  • User-1025342357 posted

    Maybe this thread can help

    http://stackoverflow.com/questions/484964/asp-net-push-redirect-on-session-timeout

    Regards

    Friday, May 4, 2012 5:27 AM
  • User-1199946673 posted

    Thanks for your information . But my questioned need to be answered . I want to redirect to login page after session expires without refreshing the page.

    Bottom line is that you cannot do this using ASP.NET (which runs on the server). You need something (like javascript) that runs on the client, which will do the redirect or a meta redirect.

    Be aware that the web is stateless!

    Also, I already explained that forms authentication has nothing to do with session. So how do you authenticate your users, using Forms authenticaton or using Session?

    Friday, May 4, 2012 5:43 AM
  • User1347670962 posted

    hans_v,

     

    I am using FormAuthentication to authenticate user , using

    FormsAuthentication.SetAuthCookie(txtEmailAddress.Text, false);

    Is there any example in Javascript to solve my problem.

     

     

     

    Friday, May 4, 2012 7:09 AM
  • User-1199946673 posted

    I am using FormAuthentication to authenticate user , using

    FormsAuthentication.SetAuthCookie(txtEmailAddress.Text, false);

    Is there any example in Javascript to solve my problem.

    Lets us identify your problem firts!? As I said, forms authentication had nothing to do with session, so why do you want to redirect to the login page when the session ends?

    Friday, May 4, 2012 7:18 AM
  • User143067745 posted

    I think you want to do that on client side:

    Add following tag under yr head tag:(Master page or in all pages you want to auto redirect)

    <META HTTP-EQUIV="Refresh" CONTENT="325;URL=../Login.aspx">

    325 is number of seconds after page will automatic refresh.If it will auto refresh on browser and session has ended on server side then will be redirected to login page.

    Note: if you are putting 300 seconds(means 5 mins) on this tag you have to code appropirate on server side to expire session in 5 mins. As many friends suggested you above.

    Friday, May 4, 2012 7:27 AM
  • User-1199946673 posted

    325 is number of seconds after page will automatic refresh.If it will auto refresh on browser and session has ended on server side then will be redirected to login page.

    When using forms authentication, redirecting the user to the login page, doesn't logout the user!

    Friday, May 4, 2012 7:57 AM
  • User143067745 posted

    You have to maintain both the times. If you are putting here 325 seconds(means 5 mins and 25 seconds) you shold put only 5 mins session expiry time in Your code(in Web.conf or global.asax).As th page will be refreshed after 325 seconds session at server already ended so server will not accept the request and It will be a anonymous requst.

    Friday, May 4, 2012 8:02 AM
  • User-1199946673 posted

    You have to maintain both the times. If you are putting here 325 seconds(means 5 mins and 25 seconds) you shold put only 5 mins session expiry time in Your code(in Web.conf or global.asax).As th page will be refreshed after 325 seconds session at server already ended so server will not accept the request and It will be a anonymous requst.

    He's using Forms authentication, which had nothing to do with session as I said many times!!!!!

    Friday, May 4, 2012 8:07 AM
  • User143067745 posted

    what do you mean by form authentication ? Means authentication via Web Froms.Each form is recognised via sissionID thats why I am talking about session.

    To recognise a previous user server maintains sessionID via cookies/url etc. at client side.At each request this id is sent to server by client.

    No consider on situation a user logged in into you site and seat idle for long time, then what?? My suggestion is about that.

    If any more help if I can??

    Try it once. 

    Friday, May 4, 2012 8:45 AM
  • User-1199946673 posted

    what do you mean by form authentication

    http://tinyurl.com/bpxhchk

     

    Friday, May 4, 2012 8:52 AM
  • User1347670962 posted

    The code which you shown

    <META HTTP-EQUIV="Refresh" CONTENT="325;URL=../Login.aspx">

    will refresh the page after 325 seconds.

    I dont want like this:(Below)

    Will refresh the page ,though i was working on the page .

    I want:(Below)

    Redirect to login page when i dont touch the page. (After Session time out).

     

    Regards,

    Shirish Manda

     

     

    Wednesday, May 9, 2012 3:50 AM
  • User143067745 posted

    You mean to say that :

    You logged into your site and visit some page for eample: xyz.aspx. And now you left you system idle for a long time. Then it should automatically redirect to login page as the session time out occurs.

    As i gave you the solution:

     Let that your session expires in 5 minutes.

    Means you set your application code to expire session in 5 minutes.

    You can do this in WEB.CONF's form tag.This code will expire session in the server side.

    It will ensure that only active session user can access your pages.

                                       Now imagine you logged in and opened a page and left it for 10mins. Your session expired in 5 mins at server but at clinet side in your browser you are still in that page you have opened.

    Ok.

    Now put that code in your aspx page.As I told you it will refresh your page in 325 seconds means 5mins and 25 seconds.

    Let your session has been expired in 5 mins. but after 5 mins and 25 seconds when this will be refreshed it will go to server for current page.

    But since session has been expired server will not allow to access the page will ask for login again.

    Put in aspx page:

    <META HTTP-EQUIV="Refresh" CONTENT="325;URL=../Login.aspx"> .

    Put in web.conf: under <System.Web>

    <authentication mode="Forms">
                
    <forms cookieless="AutoDetect" defaultUrl="Your Defaul page" loginUrl="Your Login Page" enableCrossAppRedirects="false" name="Cookie Name" protection="All" requireSSL="false" timeout="5" slidingExpiration="true"/>
            </authentication>
            <!-- Authorization-->
            <authorization>
                <allow users="*"/>
            </authorization>

    Put Followin code in MasterPage's Load event(If you don't have master page put in every page load event excepting login page):

    protected void Page_Load(object sender, EventArgs e)
        {
          /* try
            {
                String str=Session.Contents["UserName"].ToString();
               
            }
            catch (Exception exx)
            {
                Response.Redirect("~/Login.aspx");
            }
           
            */
           if (Request.IsAuthenticated)
            {
                Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetNoStore();               
               
            }
            else
            {
                FormsAuthentication.RedirectToLoginPage();
               // Response.Redirect("~/Login.aspx");
            }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2012 4:13 AM
  • User1347670962 posted

    I dont want to refresh. Because , i am doing some task on the page. It refreshes the page after specified time in the meta tag.But, the session is not Timed out.

     

    Shirish

    Wednesday, May 9, 2012 5:27 AM
  • User143067745 posted

    Sorry! I don't have any good solution for that. You can do as:

    <META HTTP-EQUIV="Refresh" CONTENT="5000;">//remove url

    Keep the time too large here and don't give any url. It will still refresh the page but will not redirect to any other page.If you can find any satisfactory solution  please do tell me too.

    Thanks a lot.

    Wednesday, May 9, 2012 5:45 AM
  • User1347670962 posted

    Hi,

    Can anybody help me ragarding my session task excluding mishra.bhupesh . 

    Task

    I dont want to refresh or set the timer in javascript. I want to redirect to Login page when session timeout.

    Shirish

    Thursday, May 10, 2012 5:37 AM
  • User-1199946673 posted

    I dont want to refresh or set the timer in javascript. I want to redirect to Login page when session timeout.

    Did it occur to you that what you ask is not possible? The web is stateless, Session timeout is an evenet that occurs on the webserver, not on the client!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 10, 2012 5:54 AM
  • User-358357840 posted

    Thanks for some very amusing dialogue.  That was  a good answer mishra, so thanks for that. I put it into the master page and it worked a treat.

    Shirish, you don't have access to the server objects that's why you can't do it in the Session_End as Hans tried to point out several times.

    I wonder what your final solution was? 

    Thanks.

    Wednesday, November 14, 2012 11:01 AM
  • User-358357840 posted

    Btw, if anyone is reading this, that doesn't work as it will refresh whether the user is idle or not.

    I used a webservice.

    Timer on client -->  call to websbervce --> webservice checks session --->  retrurns true/false  -->  if false do a window.location.href = 'tothelooginURL';

    Thanks.

    Monday, November 19, 2012 6:57 AM