How to do both sliding and absolute timeout in asp

2019-05-04 17:44发布

问题:

I have an asp.net application which is currently using forms authentication with slidingExpiration="true". In web.config, we have the following:

<authentication mode="Forms">
  <forms loginUrl="Mylogin.aspx" timeout="15" slidingExpiration="true"/>
</authentication>

This is all to spec: There is a sliding 15 minute expiration. However, we now have a new security requirement: Users must re-authenticate every 24 hours, even if they have been "active" the whole time. In other words, even if you clicked a link in the site every minute for 24 hours straight after logging in, after 24 hours, you will be automatically logged out and redirected to the login page.

But slidingExpriation is true/false only. There is no "both" feature (e.g. have slidingExpirationTimeout="15" and absoluteExpirationTimeout="1440") as far as I can tell.

Except for rolling my own solution, is there a way to implement this using the built in forms authentication?

Thanks in advance.

回答1:

You can start a new session with the current time when the user's session begins in the Global.asax file, then with every subsequent request, compare the session's value with the current time until it is >= to current time.

void Application_AcquireRequestState(object sender, EventArgs e)
{
    if (HttpContext.Current.Session != null)
    {
        DateTime started = (DateTime)HttpContext.Current.Session["SessionStarted"];
        DateTime current = DateTime.Now;
        double totalHours = started.Subtract(current).TotalHours;
        if (totalHours >= 24)
        {
            //end session
        }
    }
}

void Session_Start(object sender, EventArgs e) 
{
    // Code that runs when a new session is started
    Session["SessionStarted"] = DateTime.Now;
}

HttpApplication.AcquireRequestState Event

Occurs when ASP.NET acquires the current state (for example, session state) that is associated with the current request.