Stopping simultaneous logins (Forms Authentication)

The following code (called from a page load) will bump off users who are logged in when someone else logs in with the same credentials.

public bool ValidSession()
{

    lock (Cache)
    {

        string requestUserSessionGUID;

        if (Session["requestGuid"] == null)
        {
            // User hasn't been seen yet.. we'll let this user take over control and bump the other user off
            requestUserSessionGUID = User.Identity.Name + Guid.NewGuid().ToString();

            Session["requestGuid"] = requestUserSessionGUID;
            Cache.Insert("UserSessionID", requestUserSessionGUID);

            return true;
        }
        else
        {
            // This user has been here before, check the guid matches the one in the cache
            requestUserSessionGUID = (string)Session["requestGuid"];

            // may be first hit
            if ((string)Cache["UserSessionID"] == null)
            {
                Cache.Insert("UserSessionID", requestUserSessionGUID);
            }

            string cachedUserSessionID = (string)Cache["UserSessionID"];

            if (cachedUserSessionID == requestUserSessionGUID)
            {
                // we have a match, success
                return true;
            }
            else
            {
                // different, force logout
                FormsAuthentication.SignOut();
                Session.Abandon();
                return false;
            }
        }
    }
}
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.