Search code examples
asp.net-mvcasp.net-identity

Why Log out after verify phone number in asp.net identity?


I am using asp.net Identity in my project. In VerifyPhoneNumber view, when user confirm his phone number, he is logged out (.AspNetApplicationCookie is removed. I checked this from Resource tab inspect chrome).
Code of VerifyPhoneNumber action in ManageController:

if (!ModelState.IsValid)
{
    return View(model);
}
string phoneNumber = UserManager.GetPhoneNumber(User.Identity.GetUserId());
var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), phoneNumber, model.Code);
if (result.Succeeded)
{
    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
    if (user != null)
    {
        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    }
    ViewBag.Message = "Complete";
    return View();

}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "something wrong!");
return View(model);

Why this happens?

Update
I have set validateInterval for SecurityStampValidator to 0.


Solution

  • The ChangePhoneNumberAsync has this line:

    await UpdateSecurityStampInternal(user).WithCurrentCulture();
    

    Which causes the cookie expiration or re-validation. If you don't want it, you have to inherit from the UserManager<TUser> class (create your CustomUserManager class) and then override the ChangePhoneNumberAsync method. Just use the same code without the UpdateSecurityStampInternal line.