65.9K
CodeProject is changing. Read more.
Home

Prevent Simultaneous Logins by a Single User ID in ASP.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (7 votes)

Jul 12, 2011

CPOL
viewsIcon

64241

Using this code block, you can prevent simultaneous logins by a single User ID.

Using this code block, you can prevent simultaneous logins by a single User ID.

In order to use this code, you need to have your customized session based authentication method, which means that in your login method, you need to fetch the user from your storage (database, XML ...) and create a user object and put it in the Session. After that, the following code block should be used:

Hashtable sessions = (Hashtable)Application["WEB_SESSIONS_OBJECT"];
//"sessionsthis will be a pointer to all

Your login method will look like this:

void yourLoginMethod(string userID, string password)
{
    //put your login logic here and put the logged in user object in the session.

    //getting the sessions objects from the Application
    Hashtable sessions = (Hashtable)Application["WEB_SESSIONS_OBJECT"];
    if (sessions == null)
    {
        sessions = new Hashtable();
    }

    //getting the pointer to the Session of the current logged in user
    HttpSessionState existingUserSession = 
         (HttpSessionState)sessions[userID]; if (existingUserSession != null)
    {
        existingUserSession[WebKeys.USEROBJECT] = null;
        //logout current logged in user
    }

    //putting the user in the session
    Session[WebKeys.USEROBJECT] = user;
    sessions[user.UserName] = Session;
    Application.Lock(); //lock to prevent duplicate objects
    Application["WEB_SESSIONS_OBJECT"] = sessions;
    Application.UnLock();
}

Your logout method will look like this:

void yourLogoutMethod(string userID)
{
    //put your logout logic here, remove the user object from the session.
    Hashtable sessions = (Hashtable)Application["WEB_SESSIONS_OBJECT"];
    if (sessions == null)
    {
        sessions = new Hashtable();
    }

    Session.Abandon();
    sessions.Remove(userID);

    Application.Lock();
    Application["WEB_SESSIONS_OBJECT"] = sessions;
    Application.UnLock();
}