Check if the user was logged in without resetting the authorization timeout

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

I set authentication to expire after 30 minutes, and I need to check from the client side if the user is still logged in. I could make a simple AJAX call for this, but it will update my session and reset the timeout that I want to avoid. Using a 30-minute timeout in Javascript will only work if the client has only one tab open in my application, which I can not guarantee.

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

Alternatively, this could probably also have been done using OWIN middleware, but again, I don't know how to authenticate without resetting the timeout.

+6
source share
1 answer

Here is the function that I use to perform the feat, although I only use MVC 4. I will just call it via timed ajax post. I use it to determine how long I need to set up my time-out-ix, so I return the remaining number of seconds.

<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 Blog

+1
source

All Articles