Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user is still logged in without resetting auth timeout

I have an ASP.Net MVC 5 application, using Identity 2 for authentication (using the standard cookie authentication middleware, configured with ExpireTimeSpan = 30 minutes and SlidingExpiration = true).

I have configured authentication to expire after 30 minutes, and I need to check from client-side if the user is still logged in. I could do a simple AJAX call for that, but it would refresh my session and reset the timeout, which is exactly what I want to avoid. Using a 30 minutes timeout in Javascript would work only if the client has only one tab open on my application, which is something I cannot guarantee.

I was thinking about adding a custom attribute to an action that could check if authentication is still valid, but without resetting the timeout. Is there a way to do that?

Alternatively, this could probably also be done with an OWIN middleware, but again, I don't know how to check authentication without resetting the timeout.

like image 917
Najkin Avatar asked Sep 21 '16 06:09

Najkin


1 Answers

Here is the Function I use to accomplish the feat, although I'm only using MVC 4. I just call it through a timed ajax post. I use it to determine how long I need to set my timed ajax call for which is why I return the number of seconds remaining.

    <OutputCache(NoStore:=True, Duration:=0)> _
    Function GetExpirySeconds() As ActionResult
        Dim tkt As FormsAuthenticationTicket = Nothing
        Dim retVal As ActionResult = Json("expired")
        Response.Cookies.Remove(FormsAuthentication.FormsCookieName)
        If Request.Cookies(FormsAuthentication.FormsCookieName) IsNot Nothing AndAlso Request.Cookies(FormsAuthentication.FormsCookieName).Value <> "" Then
            tkt = FormsAuthentication.Decrypt(Request.Cookies(FormsAuthentication.FormsCookieName).Value)
            retVal = Json(Math.Floor((tkt.Expiration - Now).TotalSeconds))
            If Math.Floor((tkt.Expiration - Now).TotalSeconds) <= 0 Then retVal = Json("expired")
        End If
        Return retVal
    End Function

Blog Post for Reference: Kobi's Blog

like image 146
Steve0 Avatar answered Oct 20 '22 04:10

Steve0