Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MVC 5's identity, can't get user name right after logging in

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?

like image 466
Marcelo Myara Avatar asked May 24 '15 23:05

Marcelo Myara


People also ask

How can I get UserName in MVC?

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData , or you could just call User as I think it's a property of ViewPage .

Which string is used to obtain the user name of the current user inside an ASP NET MVC web application?

string username = currentUser. UserName; //Get UserId of Currently logged in user.


2 Answers

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.

like image 163
Alex Art. Avatar answered Oct 01 '22 17:10

Alex Art.


I've found you can go right back to the UserManager and look them up:

var user = await UserManager.FindAsync(username, password);
like image 20
DennisWelu Avatar answered Oct 01 '22 17:10

DennisWelu