Iryna
Iryna

Reputation: 162

Is it possible to change HttpContext.Current.User.Identity.Name after change username

I'm working on a ASP MVC application. And want to change username without making user logout. I am using Identity Provider version 1.0.11. My code looks like:

var updtUser = UserManager.FindById(model.UserId);

        updtUser.UserName = model.PrivateEMail;
        var res = await UserManager.UpdateAsync(updtUser);

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
               updtUser.UserName,
               DateTime.Now,
               DateTime.Now,
               false,
               "someData",
               FormsAuthentication.FormsCookiePath);

        string encTicket = FormsAuthentication.Encrypt(ticket);

        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));           

        return RedirectToAction("RedirectToDashbord", "Dashboard", new { area = "CRM"});

But after this manipulations HttpContext.Current.User.Identity.Name is not changed. Any help would be great

Upvotes: 1

Views: 1598

Answers (1)

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

You should enable immediate revocation of cookies (+):

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            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.FromSeconds(0),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

Upvotes: 1

Related Questions