I'm trying to use the MVC 5's identity solution, but got stuck on something that should be very simple: I want the login method on the AccountController to get the loged user's name right after validating the model (and I don't want to use it from the model!).
Here's a piece of my code:
var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, false, shouldLockout: false);
string NomeUsuario = "";
if (result == SignInStatus.Success)
{
NomeUsuario = User.Identity.Name; //<== getting the logged user's name
}
The problem that I'm getting is that this property is null.
After a lot of tests, I realized something odd: if I authenticate twice, on the second pass, it will work. But every time I logoff and try to login in again, it will get null on the user's name.
Any help on what's wrong with that?
At the end of its execution chain SignInManager.PasswordSignInAsync
method calls for SignInAsync
method which is basically responsible for setting an authentication cookie which contains multiple claims about a user (one of them is it's name). The reason why you can't use User.Identity.Name
in the same call with SignInManager.PasswordSignInAsync
is that User.Identity
filled out with the claims from authentication cookie (which are not parsed yet). The reason that it works on the second pass is that the cookie is there and User.Identity is properly filled. Most of the time after a successful login there is a redirect to some page. Inside this redirect action you will be able to use User.Identity
since the cookie is already set.
I've found you can go right back to the UserManager and look them up:
var user = await UserManager.FindAsync(username, password);