What set's the User.Identity.Name and User.Identity.IsAuthenticated?

1.8k views Asked by At

I want to know what set's the user identity name and change isAuthenticatedto true.

Why is User.Identity.Name an empty string and User.Identity.IsAuthenticated false after SignInManager.PasswordSignInAsync has returned Success.

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var userIdentityNameTest = User.Identity.Name; // Empty string

    var result = await SignInManager.PasswordSignInAsync(
                                             model.Email, model.Password, 
                                             model.RememberMe, shouldLockout: false);
    // result is "Success"

    userIdentityNameTest = User.Identity.Name;
    // userIdentityNameTest is still an empty string?
    // User.Identity.IsAuthenticated is still false?

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, 
                                                RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}
1

There are 1 answers

1
Pavel Timoshenko On BEST ANSWER

It seems that SignInManager.PasswordSignInAsync only validates entered data and run AuthenticationManager.SignIn if you are not using TwoFactorAuthentication. AuthenticationManager.SignIn in this case only set authentication cookie to response.

So, User.Identity is available in subsequent requests to your application. To get ApplicationUser by Name you can use ApplicationUserManager as follows:

UserManager.FindByNameAsync(model.Name)