简体   繁体   中英

_userManager.GetUserAsync(User) returns null

I am trying to check a users email confirmation status after login and then direct them accordigly.

Based on these two threads:

ASP.NET Core Identity - get current user

How get current user in asp.net core

I tried this:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    ClaimsPrincipal currentUser = this.User;
    var thisUser = await _userManager.GetUserAsync(currentUser);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}

And also this:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{   
    var thisUser = await _userManager.GetUserAsync(HttpContext.User);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}

From inside controller but thisUser is always null.

How do I check on logon that their email is confirmed and re-direct appropriately?

There's a problem to your approach, which is true for Membership and Identity : they're based on cookies . Cookies can only be read if they are sent by the client.

So, this is your flow:

  1. Set cookie
  2. Read cookie

This is wrong as explained above. Your flow should either be:

  1. Set cookie
  2. Redirect somewhere
  3. Read cookie (which now was sent by the client)

OR

  1. Set cookie
  2. Read data from wherever it's stored basing on the email you already have

I had email in model so I just looked it up directly in database.

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    _logger.LogInformation("User logged in.");

    var user = _context.Users.Single(x => x.Email == model.Email);

    if(user.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }

}

From the docs :

Identity is enabled by calling UseAuthentication . UseAuthentication adds authentication middleware to the request pipeline.

So, inside the Configure method, if you forgot setting up

app.UseAuthentication();

you will get the same result without any error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM