ASP.NET Identity - Maintain login after updating user record


In a ASP.NET MVC web application, the admin may sometimes have the need to modify his user profile, thus altering his DB AspNetUsers record and triggering a SecurityStamp regeneration.

Modifying the SecurityStamp will eventually trigger the identity validation every 30 minutes server-side and cut the user's authentication, sending him back to login.

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromMinutes(30), 
            Provider = new CookieAuthenticationProvider
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

Is there a way to prevent this from happening but allowing me to keep the validation active? (something like forcing an identity "realignment" between server and client when saving the changes on the user profile)

Thanks in advance for every advice! - Gigi


You can re-SignIn the User after the changes have been made (this code assumes you have UserManager and SignInManager available as per the default Account controller and an async ActionResult):

        ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user != null)
            await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment


TOP Ranking