ASP.net – Force a user offline as admin (destroy a session by username)

So today I came across an issue.  I created a membership system as I always do, which included allowing the admin to delete specific users.  Worked perfectly, but problem was, if a user is already logged in, it did not kill their session.  So basically this user is able to stay online even if they were deleted.

After asking people on Stack Overflow and bouncing around some ideas I decided on the following solution

  1. In my global.aspx “Application_Start” I created a new variable to hold a list of strings, so I added:
    1
    
    application("deleted_users") = New List(Of String)
  2. Next, when I deleted a user, I injected them into the application’s list of deleted users my calling:
    1
    
    System.Web.HttpContext.Current.Application("deleted_users").add(username)
  3. Finally, I needed to make sure when a user makes a request, we checked against this list of users who were deleted.  If they are in the list, kill their session.  To do this I added the following to my Global.asax:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    Private Sub MvcApplication_PreSendRequestHeaders(sender As Object, e As System.EventArgs) Handles Me.PreSendRequestHeaders
     
      'This will make sure if we are logged on, we dont need to get logged off
      If User.Identity.IsAuthenticated = False Then Exit Sub
      If Application("deleted_users").contains(User.Identity.Name) Then
        PrivateObjects.Classes.Memberships.Logout()
      End If
     
    End Sub

Something to note is by using the PreSendRequestHeaders, it processes after the page is already being sent, so the user will be allowed one more page view before his session is destroyed.  I am sure there is a different method you can use in your Global.asax that will do this at the first post, but that was enough for me!

Hope this helps anyone else who was having this issue

Pages:

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">