locked
2 minutes before session timeout, warn the user and extend it RRS feed

  • Question

  • User1754323106 posted

    Hello all,

    Here is a new requirement that I need help with. Our users request that 2 minutes before the session timeout, warn them. (i can use a global javascript to check on every page since once a page is loaded, the session reset and by default, another 20 minutes is extended). at the 18th minute, a javascript popup shows up, asking the user "You have two minutes left before being logged off. Do you want to extend the session"?

    Up to here, all is fine. But then once they hit "Extend it", then what? I don't want to refresh the page because the data they've already entered will be lost. Is Ajax needed? If so, what is the programmatic way to extend the current session? (not modifying web.config just to be clear)

    Also, say they are talking to someone and did not see the javascript confirmation during the 2 minute. Is there anyway to "hold" the session, till the user decides to do something?

    Thanks


    Friday, January 18, 2008 6:10 PM

Answers

  • User2022958948 posted

    Hi,
    At every postback, session will be refreshed and the time of session will be initialized.
    So, there is an available approach that is using JavaScript to simulate the left time of session.
    You can try the code as below. At first, set the lefttime as the timeout of session.

    <script type="text/javascript">
    var lefttime=25;
    var interval;
    interval = setInterval('change()',60000);
    
    function change()
    {
       lefttime--;
       if(lefttime<=2) alert("the session will be off, left time is "+lefttime+" second!")
    }
    </script>
    Hope it helps.
     
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 21, 2008 11:16 PM
  • User-717199307 posted

    I feel, you do anything, but unless you reach back to your server, your session time will not get extended.  Once you go back to Server, your page will be reloaded.    For all the user entry controls, set the ViewState as True.  Through javascript pop up a messagebox to client and if he clicks ok then execute suitable code at serverside.  Since the ViewState of controls is True, the user data will not go and same data will appear when page is loaded.    Alternatively, you can use Page callback method instead of Postback Method.   In Callback Method the user will not even feel that page has been submitted to the Server.

    Hope this will help you.

    KBN Sarma

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 21, 2008 11:25 PM

All replies

  • User303162096 posted

     

    Great article

    http://blogs.msdn.com/nikhiln/archive/2007/06/21/detecting-session-timeout-in-asp-net-2-0-web-applications.aspx

    I would forward the user to a page at first and then work on a javascript function that gets called in the global.aspx to give you your message box.  Either way hope this helps. 

    Friday, January 18, 2008 6:48 PM
  • User807886609 posted

    I'm not sure this requirement even makes any sense, since the Session Timeout is a SLIDING expiration value. In other words, when a user requests a page, their session timeout automatically gets extended.

    Friday, January 18, 2008 7:57 PM
  • User1754323106 posted

    Hello pbromberg,

    Yes, what you said is correct. However, the issues is what happens AFTER a page is loaded.

    Say they typed some text into a text area, trying to write an article.  A coworker comes by and start talking to them for 25 minutes, when the little chit chat is over, (because the page has not loaded again since then),  not knowing the session has timed out, the users continued their typing on the article, click "Save"... bang, session timed out, went back to login page and his work therefore is lost!

    That's the scenario.


    Friday, January 18, 2008 8:35 PM
  • User1754323106 posted

    Hello Bcanonica,

    Took a look at the article, it's checking if the session has already timed out.... but I need to check 2 minutes before the timeout and provide user the option to "Slide" the session further without auto forwarding to another page (because the user is writing a blog / article, don't want them to lose their work)

    Thanks though.

    Friday, January 18, 2008 8:49 PM
  • User1754323106 posted

    Just FYI. Here is a screen shot of what Chevy Chase Bank did when I stayed on a page for too long with no activity (except scrolling around)

     

    Friday, January 18, 2008 9:05 PM
  • User2022958948 posted

    Hi,
    At every postback, session will be refreshed and the time of session will be initialized.
    So, there is an available approach that is using JavaScript to simulate the left time of session.
    You can try the code as below. At first, set the lefttime as the timeout of session.

    <script type="text/javascript">
    var lefttime=25;
    var interval;
    interval = setInterval('change()',60000);
    
    function change()
    {
       lefttime--;
       if(lefttime<=2) alert("the session will be off, left time is "+lefttime+" second!")
    }
    </script>
    Hope it helps.
     
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 21, 2008 11:16 PM
  • User-717199307 posted

    I feel, you do anything, but unless you reach back to your server, your session time will not get extended.  Once you go back to Server, your page will be reloaded.    For all the user entry controls, set the ViewState as True.  Through javascript pop up a messagebox to client and if he clicks ok then execute suitable code at serverside.  Since the ViewState of controls is True, the user data will not go and same data will appear when page is loaded.    Alternatively, you can use Page callback method instead of Postback Method.   In Callback Method the user will not even feel that page has been submitted to the Server.

    Hope this will help you.

    KBN Sarma

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 21, 2008 11:25 PM
  • User1754323106 posted

    KBN, that's it! callback. That's what i will do. I already got the javascript in place, so I was looking for really, a solution of how to extend the session time. I'll look into this now. Thanks a lot.

    Tuesday, January 22, 2008 7:27 PM
  • User-717199307 posted

    All the best.  Can you send the Call Back Code to me since I am also looking for this type of support in my web page and I am weak in Javascript.  My Mail ID is kbnsarma@yahoo.com

    Regards,

    KBN Sarma

     

    Tuesday, January 22, 2008 11:20 PM
  • User-219302939 posted

    All the best.  Can you send the Call Back Code to me since I am also looking for this type of support in my web page and I am weak in Javascript.  My Mail ID is kbnsarma@yahoo.com

    Regards,

    KBN Sarma

     

     

    Perhaps this may be usefull for you....

     

    http://www.common-controls.com/en/resources/docs/CC_Eventhandler_EN.pdf

     

    Wednesday, January 23, 2008 4:59 AM
  • User-717199307 posted

    Thank you Mr. Shantanu. 

    KBN Sarma

    Wednesday, January 23, 2008 5:11 AM
  • User1754323106 posted

    It's an old thread and I just want to post the solution we added to our software.

    1) In your code-behind, first add in the code to figure out the form authentication timeout value you added in web.config
    2) Find out user's preference, i.e how many minutes before timeout, they want the warning? (We stored that in the user Profile object)
    3) Have asp.net register the javascript with those values to the client side.
    4) Client side script start counting based on those values and warn the users.


    Codebehind

    protected void Page_Load(object sender, EventArgs e)
    {
    this.keepAlive();
    }

    private int GetFormsTimeout()
    {
    System.Xml.XmlDocument x = new System.Xml.XmlDocument();
    x.Load(Request.PhysicalApplicationPath + "/web.config");
    System.Xml.XmlNode node = x.SelectSingleNode("/configuration/system.web/authentication/forms");
    int Timeout = int.Parse(node.Attributes["timeout"].Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
    return Timeout;
    }

    private void keepAlive()
    {
    //figure out the full url of the logout page configured in web.config + the return url which is the current page

    String logoutUrl = FilesUtil.LoginUrl + FormsAuthentication.LoginUrl+"?ReturnUrl="+Request.Url;

    String minutesToWarning = "";
            //figure out how many minutes before time out the user wants to get warned. 

    String minutesBeforeLoggedOut = Profile.UserPreferences.warningInMinutesBeforeLoggedOut;
    if (minutesBeforeLoggedOut == null || minutesBeforeLoggedOut == "")
    {
    minutesBeforeLoggedOut = "1";
    }

    //if the user selected "-1", then it never gets timedout. If not, figure out, how many minutes after the page loaded, give the user the warning
    if (!minutesBeforeLoggedOut.Equals("-1"))
    {
    int formsTimeout = GetFormsTimeout();
    minutesToWarning = Convert.ToString(formsTimeout - Convert.ToInt32(minutesBeforeLoggedOut));
    }
    String script = @"
    <script type='text/javascript'>
    var minutesToWarning = "
    + minutesToWarning + @";
    var minutesBeforeLoggedOut = "
    + minutesBeforeLoggedOut + @";
    var loginUrl = '"
    + logoutUrl+ @"';
    </script>
    "
    ;

    if (!ClientScript.IsClientScriptBlockRegistered("WarnTimeOut"))
    ClientScript.RegisterClientScriptBlock(typeof(Page), "WarnTimeOut", script);
    }

     
    Javascript used

     

      

    					<script  type="text/javascript">

    var secondsPassed = 0;


    function ShowTimePassed()
    {
    minutesBeforeLoggedOut = parseInt(minutesBeforeLoggedOut);
    secondsPassed+=1;

    if(minutesBeforeLoggedOut == -1)
    {
    if(secondsPassed == 30)
    {
    var img = new Image(1,1);
    img.src = 'KeepAlive.aspx?date='+escape(new Date());
    secondsPassed = 0;
    }
    }
    else{
    if(secondsPassed ==minutesToWarning*60)
    {
    var answer;

    var currentTime = new Date();
    var expiredTime = new Date();
    var minutes = expiredTime.getMinutes();
    minutes+=minutesBeforeLoggedOut;
    expiredTime.setMinutes(minutes);

    if(minutesBeforeLoggedOut==1)
    answer = confirm("It is now "+ currentTime.toLocaleTimeString()+" You have "+minutesBeforeLoggedOut+" minute left before getting logged out. Do you want to extend the session?");
    else
    answer = confirm("It is now "+ currentTime.toLocaleTimeString()+" You have "+minutesBeforeLoggedOut+" minutes left before getting logged out. Do you want to extend the session?");
    if(answer){
    var img = new Image(1,1);
    img.src = 'KeepAlive.aspx?date='+escape(new Date());
    secondsPassed = 0;
    currentTime = new Date();
    if(currentTime>expiredTime){
    alert("You've exceeded the time needed to extend the session. You will be logged out now");
    window.location = loginUrl;
    }
    }
    }
    }
    }

    window.setInterval('ShowTimePassed()', 1000);
    </script>
     

     

    Thursday, April 16, 2009 9:37 AM
  • User1754323106 posted
    btw, just to clarify, after research, i realized the subject of the thread is wrong. I did not mean session time out, i meant forms authentication time out. They are two different things.
    Thursday, April 16, 2009 9:38 AM
  • User1801871119 posted

    Great code. works great for me.

    But i dont understand when use will click OK (in timeout warning window). How it will refresh the session. i dont see page refreshing?

    Thanks in advance.

    Tuesday, July 14, 2009 7:27 AM
  • User1801871119 posted

     i dont understand what is the use of var img

     

    if (answer) {
                            var img = new Image(1, 1);
                            img.src = 'default.aspx?date=' + escape(new Date());
                            secondsPassed = 0;
                            currentTime = new Date();
                            if (currentTime > expiredTime) {
                                alert("You've exceeded the time needed to extend the session. You will be logged out now");
                                window.location = loginUrl;
                            }
                        }

     

    any ideas?

    Tuesday, July 14, 2009 10:33 AM
  • User1754323106 posted

    Hey jagjot,

    forgot to mention, there is a blank "keepalive.aspx" in the directory. In the javascript code, after you clicked okay, an empty image object was costructed like so

        var img = new Image(1,1);
    img.src = 'KeepAlive.aspx?date='+escape(new Date());

    that will hit the keepalive.aspx page and such extend the user session.

    As for the last piee of the code, users sometimes return to the window way after the warning period has expired. That was a measure to let the users
    know that, even if they clicked "okay", it's no use now, because they did not take any action during the warning period. ASP.NET by default
    already timed you out, there is nothing we can do now. Such, we redirect them back to the login page
    Friday, July 17, 2009 11:14 AM
  • User-1346602782 posted

    Hope this helps,

    msdn.microsoft.com/en-us/library/ms178208.aspx

    www.developer.com/net/asp/article.php/3485991

    www.codeproject.com/KB/aspnet/ClientCallBackAspNet2.aspx

    Friday, July 17, 2009 12:02 PM
  • User903913376 posted

    Sliding forms Authentication only refreshes the auth ticket after the ticket is 1/2 way expired.

    If a user has a 30 min ticket & refreshes their browser every min for 14 min, then does nothing for 16 minutes, they get logged out!

    You need to test for when Auth ticket is set & how old it is. If it is older than 15 min and you refresh, it gets reset to 30 mins...

    Thursday, December 3, 2009 4:33 PM
  • User2130120374 posted

    Hi Liming

                The code which u gave is not working for me....plz if u have any othe solution for "2 minutes before session timeout, warn the user and extend it" this provide me.


    Sunday, March 28, 2010 6:31 AM