Update Identity User Claims in Web API
Main problem is that claim which represents user's name is not updated in ClaimsIdentity
you are using in the last step.
The easiest way to perform the update is to use SignInManager<TUser, TKey>.SignIn
method
signInManager.SignIn(identityUser, isPersistent: false, rememberBrowser: false);
This is also an ASP.NET Identity idiomatic way since it is using associated IClaimsIdentityFactory
to create claims for new identities.
Complete example
static async Task<IdentityResult> UpdateEmailAsync<TUser>( IPrincipal principal, UserManager<TUser, string> userManager, SignInManager<TUser, string> signInManager, string newEmail) where TUser : class, IUser<string>{ string userId = principal.Identity.GetUserId(); IdentityResult result = await userManager.SetEmailAsync(userId, newEmail); if (result.Succeeded) { // automatically confirm user's email string confirmationToken = await userManager.GenerateEmailConfirmationTokenAsync(userId); result = await userManager.ConfirmEmailAsync(userId, confirmationToken); if (result.Succeeded) { TUser user = await userManager.FindByIdAsync(userId); if (user != null) { // update username user.UserName = newEmail; await userManager.UpdateAsync(user); // creates new identity with updated user's name await signInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } // succeded return result; } } // failed return result;}
Then you can just call it from your code
string newEmail = AntiXssEncoder.HtmlEncode(value.Email, true);IdentityResult result = await UpdateEmailAsync(identityUser, UserManager, SignInManager, newEmail);if (result.Succeeded){ return Ok();}