Iterating through existing session objects

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

Is there a way to iterate over existing sessions and destroy them?

+2


source to share


5 answers


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);
}

      

You can now iterate through your sessions like this



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

foreach (var session in sessions)
       ...

      

To kill other sessions, you can check the method Session_Start

so that the old session discards it. It 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);
}

      

+2


source


you can save registered users in the database and check if they are logged in, you can prevent them from logging in again. using the Session_Start method in the Global.asax section.



0


source


The short answer is no.

Long answer: you need to implement your own session provider. There is no reason for one session to refer to any other session for security reasons. You will have to get by and implement your own session management.

0


source


Once I implemented this, I stored the user ids (or something unique) in an application variable, in a dictionary, or in an array. Easily check for the presence of a user ID in the application dictionary at login time. The only real problem is people who don't log out and just close the browser. You will never find a reliable way to detect this event.

0


source


Turn off the cuff:

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

In each request, you will need to check that the UserID (stored in the session) and SessionID match the values ​​stored in the Lookup table as an authentication step.

0


source







All Articles