Search code examples
asp.net-mvc-3sqlmembershipprovider

How can I block the same user from logging in on another machine?


I basically want to setup in my LogOn Action a conditional statement that looks at the username, and determines that username is already logged in.

At which point the user should be informed.

That account is logged in, if you think you've been hijacked...yada yada yada.

I thought I could add something after this conditional, is there something like my made up method Membership.CheckIfUserIsOnline(string username) out there already?

   if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            //See the line below, I made this method up.
            if (Membership.CheckIfUserIsOnline(model.UserName){
                ModelState.AddModelError("", "Someone else is logged into this account.");
            }

Solution

  • If you're using Session State, I would store (ideally in an application-wide cache or alternatively in your application database) a record keyed on the User ID, storing the Session ID.

    Then, check the logged-in User ID against the current Session ID when you're looking to detect multiple logons. If the Session ID stored in the database doesn't match the Session ID of the current Session, that may indicate multiple logons.

    You have to deal with expiring the values from the data store (which is why an application-wide cache may be better than the application database) and with normal termination of a session (on logoff), but if you're only using it to alert the user, it's probably good enough.