Question

I want to be able to kill existing sessions for the same username when someone logs in to prevent multiple people from using the same login.

Is there a way to iterate through existing sessions and kill them?

Was it helpful?

Solution

Add this to your global.asax

protected void Application_Start(object sender, EventArgs e)
{
    Application["sessions"] = new List<HttpSessionState>();
}

protected void Session_Start(object sender, EventArgs e)
{
    var sessions = (List<HttpSessionState>)Application["sessions"];
    sessions.Add(this.Session);
}

protected void Session_End(object sender, EventArgs e)
{
    var sessions = (List<HttpSessionState>)Application["sessions"];
    sessions.Remove(this.Session);
}

Now you can iterate through your sessions like this

var sessions = (List<HttpSessionState>)Application["sessions"];

foreach (var session in sessions)
       ...

In order to kill other sessions in you could check in the Session_Start method for the old session abandon it. That might look something like this.

protected void Session_Start(object sender, EventArgs e)
{
    var userId = (int)this.Session["userId"];
    foreach (var session in sessions)
        if ((int)session["userId"] == userId)
           session.Abandon();

    var sessions = (List<HttpSessionState>)Application["sessions"];
    sessions.Add(this.Session);
}

OTHER TIPS

you can save the logged users to database and check if they have already logged in, you can prevent them to login again. using the Session_Start method under Global.asax.

Short answer: no.

Long answer: you need to implement your own session provider. There's no way for one session to reference any other session, for security reasons. You'd have to go around and implement your own session management.

The one time I implemented this, I stored user ids (or something unique) in an Application variable, a Dictionary or an Array. It's easy to check for the existence of the User ID in the Application Dictionary at log in time. The only real issue is people who don't log out and just close the browser. You'll never find a good reliable way to detect this event.

Off the cuff:

On Session_Start (usually a successful login), in store the user's UserID and SessionID in a lookup table (or new column in the user table).

On each request you would need to validate that the UserID (stored in Session) and SessionID match the values stored in the Lookup table as an authentication step.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top