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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With