Home > OS >  Howto logout from all devices if authentication provider is Microsoft.Owin
Howto logout from all devices if authentication provider is Microsoft.Owin

Time:12-16

Logging out a user's session has always worked for me without problems, by using the HttpContext.GetOwinContext().Authentication.Signout() method.

However, a user might have loggedin from at least a dozen different devices (phone, tablet, other PCs, etc).

I want to implement that when the user changes his password, to force a logout on all other devices except the device where the user did the change of password.

How to accomplish this?

CodePudding user response:

Assuming you are using ASP.NET Identity 2, you can use UpdateSecurityStampAsync and then set OnValidateIdentity in the CookieAuthenticationOptions settings

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    Provider = new CookieAuthenticationProvider
    { 
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(0),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
...
}

Then after changing password successfully:

signInManager.AuthenticationManager.SignOut();     

//updating the security stamp invalidates all other sessions
await userManager.UpdateSecurityStampAsync(currentUser.Id);

await signInManager.SignInAsync(currentUser, false, false);
  • Related