Asp.net Identity : User.Identity.GetUserId() is always null and User.Identity.IsAuthenticated is alway false

user2376512 picture user2376512 · Aug 22, 2014 · Viewed 8.4k times · Source

See my code below:

var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        string UserId = User.Identity.GetUserId(); 
        return RedirectToAction("ClientDetails","Home");
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.RequiresVerification:
        return RedirectToAction("SendCode", "Account", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
    default:
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
}

The UserId is always null and User.Identity.IsAuthenticated is always false. But I can view the View ClientDetails which requires authentication.

Answer

Dewey picture Dewey · Jan 28, 2015

I assume your example is the code from your AccountController.Login() method. I had the same problem as you but discovered that the User object won't be populated until the next request. Try this approach:

case SignInStatus.Success:
    return RedirectToAction("DoWork", "Account");


public async Task<ActionResult> DoWork()
{
    //this works
    string UserId = User.Identity.GetUserId();
    //return to View or Redirect again
}