Invalidate ClaimsPrincipal after it has been modified

故事扮演 提交于 2019-12-01 14:21:17

When looking at MS built-in template, I noticed that they always makes a call to SignInManager.SignInAsync, after changing user credentials (e.g. password, 2 Factor Authentication, etc).

I also noticed that the Claims are updated once the user logs out and logs back in... so after changing "FirstName" which is stored in a Claim, I called SignInManager.SignInAsync to re-signin the User... this way, the Claims are updated:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateFirstName(string firstName)
{
    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<long>());
    user.FirstName = firstName;

    // update FirstName which is stored in a Claim
    var result = await UserManager.UpdateAsync(user);

    if (result.Succeeded)
    {
        // re-signin the user, to refresh the Claims
        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

        // you need to redirect after calling SignInAsync, so claims are refreshed
        return RedirectToAction("Index"); 
    }

    // add some error message...
    return View();
}

Note: As shown in the question, I am storing the Claims in Cookie.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!