Search code examples
asp.netasp.net-mvcasp.net-core-mvcasp.net-identity

Asp Core Identity, How to get userId after login?


I have 2 controllers named : AdminProfileController And UserProfileController. I want get userId and user role directly after logged in because i want user go to AdminProfileController if user had Admin Role and go to UserProfileController if user had User Role.

My Code

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Model Erroe");
                return View(model);
            }
        }
        return View(model);
    }


    private IActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        else
        {
            if (User.IsInRole("Admin"))
            {
                return Redirect("/AdminProfile/Index");
            }
            else
            {
                return Redirect("/UserProfile/Index");
            }
        }
    }

But User.IsInRole("Admin") always is false, I also tried to get the userId by this code :

 string userId = _userManager.GetUserId(HttpContext.User);

But it returns also null . How can i get userId or role directly after logged in to navigate to Specified path?


Solution

  • Reason you don't get get value you expect from User.IsInRole because this reads roles from a cookie and cookie is not yet set at the point where you use this method.

    For the same reason you don't get anything out of _userManager.GetUserId(HttpContext.User). At the point of execution HttpContext.User is not set yet.

    At the point where you do the checks, to determine if user is in role, best thing to do is to use UserManager.IsInRoleAsync method. This methods checks the database for roles. Also to get user object you can use UserManager.FindByNameAsync method and pass model.UserName value there. You'll get your ApplicationObject instance back to you and will get your userId for role checking.