Logout user from all browsers

2019-07-15 05:34发布

问题:

I'm using FormsAuthentication mechanizm and auth users via

FormsAuthentication.SetAuthCookie(...);

Can I logout current user from all browsers somehow?

回答1:

Add a guid parameter inside to authentication parameters. Also save guid to a session table for example like this;

  public class sessionLog
  {
     public int UserID { get;set;}
     public string Guid {get;set;}
     // ... may be you can add IP, datetime or isSessionClosed etc
  }

When login add a row into table, save guid inside the cookie. Check the user authentication with userID and guid is enabled.

Remove row logout with the guid or remove all with userID for close all sessions.



回答2:

Technically, that's impossible. The user is authenticated via an encrypted cookie set within the browser. Logging the user out merely invalidates that cookie. There's no way to then invalidate cookies that may exist in other browsers or even other machines.

The only way you could potentially achieve something like this is to indicate in some way, tied to the user's account, that they have been logged out. This could be an additional column on your profile table or some other type of persistent storage medium. Whatever you do, you would then need to look at this when an authenticated user accesses some portion of your site. If they have been previously logged out, you would then log them out again on that browser/machine instance. When they log in again, you would clear whatever you previously set, so that they would remain authenticated. In other words, you have to check and invalidate the auth cookie in each browser when the user attempts to access the site from that browser. There's no way to do anything until the user accesses your site from that particular browser.



回答3:

You need to store a list of users logged in on an application variable. If a user with that Guid tries to login again you can display a message that they are already logged in elsewhere....

I don't think you can control users session once it has been granted, but you could add logic to deny access to functionality if an attempt to login from elsewhere (I'm not sure why you would want to do it though because logging in from different devices is not always done maliciously).