0

I am using ASP.NET Identity 2 to manage users and would like to know if there is a function available through UserManager to check if a particular user is authenticated or logged in currently. By this I mean, for an administrator of the site to check if a given user is logged in or not. I do know, there is User.Identity.IsAuthenticated that is for the current HTTP request only. How do I go about implementing this otherwise?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
user2813261
  • 625
  • 1
  • 8
  • 18
  • The web is Inherently Stateless. So there isn't anything you can ask the website directly if a user is logged in. After all, I could login then close my browser. So am I logged in or not? I believe that FormAuthentication would simply look at the Last Login or Update Status date (I can't remember the field at the moment) and compare it to a timespan (say 30 minutes) to say if a user or users are currently logged in. – Erik Philips May 22 '14 at 22:39

1 Answers1

2

No, there is no functionality in the base Identity 2.0 that keeps track of currently logged in users, you would have to add this yourself. Because of the way MVC works (really because of the statelessness of HTTP) the server never has a definitive idea of whether the client is logged in or not.

At the most basic level, being "logged in" can be defined as being from when:

  • The user is authenticated, and the authentication ticket is written as a cookie to the browser

until either one of the following happens:

  • The user clicks the Logout link

  • The authentication ticket cookie expires or is deleted

Since the ticket exists on the client side, the server only knows exactly when a user has logged out in the first case. In the second case, it only knows whenever the next HTTP request from that client is made. And unless you are using some background AJAX polling or other client server communication like SignalR, the server won't know difference if a client is just sitting idle, or they've closed the browser or moved on to another page.

If you're keen on keeping track of this yourself, you'll have to extend the IdentityUser class to add a timestamp of the user's last login or activity (and update this information every time the user makes a request), and then compare that to the current time, and then decide that users with no activity within a certain time span will be considered logged out. For example you may determine that a user that hasn't contacted the server in the last 30 mins has "logged out", but you'll never know for sure unless they actually gone through the Account\Logout controller method.

jmoerdyk
  • 5,544
  • 7
  • 38
  • 49