0

I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}
MaxW
  • 421
  • 1
  • 7
  • 22
Andrea
  • 247
  • 2
  • 4
  • 14

3 Answers3

0

To me it looks like you are logging the user in and immediately trying to access the user info. The httpContext has not had the chance to update and still reflects the time when there was no user logged in. Try moving your user info retrieval logic to "createpost" where it gets executed on the next http roundtrip.

    public async Task<IActionResult> createpost()
    {
        var userData = await mUserManager.GetUserAsync(HttpContext.User);
        Debug.WriteLine(userData.Id);
        Debug.WriteLine(userData.UserName);
        Debug.WriteLine(userData.Email);
        return View();
    }
Martin
  • 87
  • 1
  • 5
  • If that does not work, make sure that your authentication system works. You could, for example, decorate the createpost() action with the [Authorize] attribute. If your current user can execute the createpost() action, you should be able to access the user data exactly as shown. – Martin May 30 '19 at 09:23
  • thanks for your answer, it helped me, mUserManager.GetUserName(HttpContext.User); after that I use the logged username to access from database – Andrea May 31 '19 at 21:33
0

You've got two issues. First, GetUserAsync relies on the principal being set in HttpContext, which hasn't occurred yet, so that method will fail. There must be an intervening request before you can access the user that way.

What you can do is pull the user out directly using something like FindByIdAsync, which you're attempting to do already. However, you're trying to find the user based on the id of the user instance you tried to retrieve via GetUserAsync. Since that failed, there will be no user, and thus no id to use in this lookup, causing it to fail as well. It doesn't even make sense to do this, as if you had the user already to get the id from, there'd be no point in looking that user up by its id.

So, what you need to do is look the user up by information you actually do have, which based on your code, is username. Therefore, do:

var user = await mUserManager.FindByNameAsync(username);
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

The reason is that the user will be available for next request, you could not get the user in this current request,let alone user's name.

Ryan
  • 19,118
  • 10
  • 37
  • 53