4

So I'm using the default ASP.Net MVC template and sorting out things I don't need from the project. The user keeps getting logged in again if they change things like their password or phone number.

For example, in the ManagerController.cs file I keep seeing things like

    //
    // POST: /Manage/ChangePassword
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId<int>(), model.OldPassword, model.NewPassword);
        if (result.Succeeded)
        {
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
            if (user != null)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
            }
            return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
        }
        AddErrors(result);
        return View(model);
    }

The relevant part of that code is

            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<int>());
            if (user != null)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
            }

What is the purpose of this repetitive code? Do I need it? I'm removing 2 factor authorization and phone verification, by the way.

Slight
  • 1,541
  • 3
  • 19
  • 38

2 Answers2

2

Signing the user in again with SignInManager.SignIn should cause the user auth cookie (if using application cookies which is default) to be regenerated and the security stamp for the user to be regenerated along with it. The security stamp should be changed everytime a user role, claim, login, or anything else stored in the ClaimsIdentity (User.Identity) changes. Otherwise, the user will be using an outdated cookie (which is a serialized ClaimsIdentity) that does not match the database. If that happens they could have roles that were removed or not have roles that were added among other things.

There are other ways of regenerating the security stamp which is actually all the is needed because a auth cookie with an invalid security stamp will simply be regenerated to contain the correct information instead of rejecting the request as unauthorized. However, this is how it is done be default and may be all that is needed.

Slight
  • 1,541
  • 3
  • 19
  • 38
1

Do I need it?

Yes (see below)

What is the purpose of this repetitive code?

Assuming you're using Identity, then reloading all the claims is usually necessary. I'm not sure if any of the claims have any password hashes or seeds (if so then definitely) but any role changes or claims changes this is necessary for later code (in a view perhaps) to validate the user correctly.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150