0

I have a web application that employees log in to do stuff. What Im trying to achieve is: When a user logs in from a computer, if he is already logged in on another computer, that must be logged out. The web app is MVC Asp.Net Core 2.2 Code first. I have added a signInManager in startup and edited the PasswordSignInAsync method. I login the system from two different devices. When I click something on the screen from the first computer that I loggedin, it redirects to logout. It seems like working. But Im not sure if this is the right way of doing this. The code I added is: await UserManager.UpdateSecurityStampAsync(user); Inside PasswordSignInAsync method.

Inside the startup class ConfigureServices method I added

     'services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddSignInManager<SignInManagerX>()'

Then in SignInManagerX class which is inherited from SignInManager I overrided the PasswordSignInAsync

public override async Task<SignInResult> 
PasswordSignInAsync(ApplicationUser user, string password,
       bool isPersistent, bool lockoutOnFailure)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        var attempt = await CheckPasswordSignInAsync(user, password, 
lockoutOnFailure);
//Here is added
        if (attempt.Succeeded)
        {
            await UserManager.UpdateSecurityStampAsync(user);
        }
//Add end
        return attempt.Succeeded
            ? await SignInOrTwoFactorAsync(user, isPersistent)
            : attempt;
    }

Is this the right way ? or I should add a table to db for logins which holds the info if the user is already logged in on another Ip. Then Logging out that user from all computers if the last and current login attempt is true ?

1 Answers1

0

Yes , the primary purpose of the SecurityStamp is to enable sign out everywhere.

The basic idea is that whenever something security related is changed on the user, like a password, it is a good idea to automatically invalidate any existing sign in cookies, so if your password/account was previously compromised, the attacker no longer has access.

Reference : https://stackoverflow.com/a/19505060/5751404

You can set validateInterval to TimeSpan.Zero for immediate logout .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148