Guerrilla
Guerrilla

Reputation: 14846

_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?

Upvotes: 4

Views: 7668

Answers (3)

Tân
Tân

Reputation: 1

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.

Upvotes: 0

Guerrilla
Guerrilla

Reputation: 14846

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");
    }

}

Upvotes: 0

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

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

Upvotes: 4

Related Questions