Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

jquery - How To Detect MVC 3 Session Expiration via JavaScript

I have an MVC 3 site with a session timeout of 2 minutes.

If the user doesn't interact with the page within 2 minutes, they should be automatically forwarded to the login screen as soon as 2 minutes hits (not when they interact after 2 minutes).

Any time the user interacts with the page while the session is still active, the session timeout needs to be reset to 2 minutes from that time.

Our current implementation is as follows (source code is below):
1. When user logs in, call setTimeout(checkSession, 120000)
2. When the user interacts with the page, call renewSession()
3. After checkSession() runs, call setTimeout(checkSession, 120000)

The issue in the current implementation is that, there is a loophole where the session will be valid for longer than 2 minutes.

For example:
- user logs in at 12:00 (session should expire at 12:02)
- at 12:01 the user interacts with the page
- renew session is called which resets the session timeout to 2 minutes (session should expire at 12:03)
- at 12:02, first checkSession() runs and returns valid, checkSession() gets set to run again at 12:04
- session should still expire at 12:03, but it doesn't because checkSession() is also renewing the session timeout
- if user doesnt interact with site before 12:04, checkSession() will run and log the user off, however, it's been 3 minutes since the last user activity

My initial solution was to call setTimeout(checkSession, 120000) when renewSession() is called but since checkSession() renews the session this keeps it alive forever.

Is there anyway to prevent checkSession from renewing the session or can someone point me to a better solution for accomplishing this?

$(document).ready(function() {
    setTimeout("checkSession();", 60000);

    $("body").mouseup(function () {
        renewSession();
    });

    $("input").blur(function () {
        renewSession();
    });

    $("input").focus(function () {
        renewSession();
    });
});

function checkSession() {
    $.ajax({
        url: "/Account/CheckIfSessionValid",
        type: "POST",
        success: function (result) {
            if (result == "False") {
                window.location = "/Account/LogOff";
            }
        },
        complete: function () {
            setTimeout("checkSession();", 60000);
        }
    });
} 

function renewSession() {
    $.ajax({
        url: "/Account/RenewSession",
        type: "POST",
        data: {
            __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
        }
    });
}

public ActionResult CheckIfSessionValid()
{
    if (Session["GoldenTicket"] == null)
    {
        Session.RemoveAll();
        Session.Abandon();
        FormsAuthentication.SignOut();
        return Json("False");
    }

    return Json("True");
}

[HttpPost]
[ValidateAntiForgeryToken]
public void RenewSession()
{
    Session["GoldentTicket"] = "True";
}


protected void Session_End(object sender, EventArgs e)
{
    Session.Clear();
    Session.Abandon();
    Session.RemoveAll();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var checkTimeout;

$(document).ready(function () {
    checkTimeout = setTimeout(checkSession, 900000);
});

function checkSession() {
    $.ajax({
        url: "/Account/CheckIfSessionValid",
        type: "POST",
        success: function (result) {
            if (result == "False") {
                window.location = "/Account/LogOff";
            }
        },
        complete: function () {
            setupSessionTimeoutCheck();
        }
    });
}

function setupSessionTimeoutCheck() {
    clearTimeout(checkTimeout);
    checkTimeout = setTimeout(checkSession, 900000);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...