Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 661
topcool Avatar asked Jan 16 '18 22:01

topcool


People also ask

How do I find my UserName for net core?

Special Note: If you want ONLY get the currently logged in Windows username (useful for Windows domain networks) all you need is to change the website's authentication to Windows & calling “User.Identity.Name”.

How can I get UserName in asp net?

Use the UserDomainName property to obtain the user's domain name and the UserName property to obtain the user name. On Unix platforms the UserName property wraps a call to the getpwuid_r function. If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user.

What is HttpContext user identity name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

What is IHttpContextAccessor?

It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any. ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it.


2 Answers

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.

like image 132
trailmax Avatar answered Sep 28 '22 08:09

trailmax


I can solve it. just try it:

[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)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);
            string existingRole = _userManager.GetRolesAsync(user).Result.Single();

            //string userid = user.id;
            return RedirectToLocal(returnUrl,existingRole);
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Model Erroe");
            return View(model);
        }
    }
    return View(model);
}





private IActionResult RedirectToLocal(string returnUrl,string roleName)
{
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }
    else
    {
        if (roleName == "Admin")
        {
            return Redirect("/Admin/User");
        }
        else
        {
            return Redirect("/User/UserProfile");
        }

    }
}
like image 45
topcool Avatar answered Sep 28 '22 07:09

topcool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!