Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get role/s of current logged in user in ASP.NET Core MVC

How can I get the logged in user's role/s in ASP.NET Core MVC? I want to get role details as soon as user logs in into the application, but by using following code I am not able to retrieve the role details

public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {

        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

        if (result.Succeeded)
        {
            _logger.LogInformation(1, "User logged in.");

           bool available = User.IsInRole("Admin"); 
            return RedirectToLocal(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning(2, "User account locked out.");
            return View("Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return View(model);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

Also, I have used the below methods like

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

var userRoles = await _userManager.GetRolesAsync(user);

Still, I am not able to get the role details. Can anyone please help on this?

like image 548
XamDev Avatar asked May 31 '16 11:05

XamDev


People also ask

How can get current user role in asp net core?

var user = new ApplicationUser { UserName = model. Email, Email = model. Email }; var userRoles = await _userManager. GetRolesAsync(user);

How can we get logged in user role in asp net identity?

After getting the Identity User from SignInManager , call GetRolesAsync on UserManager and pass identity user as parameter. It will return a list of roles the identity user has enrolled in.


2 Answers

You may want to consider trying to load the actual ApplicationUser object via the FindByEmail() or some other method and passing that object into the GetRolesAsync() method as seen below :

// Resolve the user via their email
var user = await _userManager.FindByEmailAsync(model.Email);
// Get the roles for the user
var roles = await _userManager.GetRolesAsync(user);

A more complete example might look like :

[HttpPost("Auth/SignIn")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SignIn(SignInViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, false);
        if (result.Succeeded)
        {
            // Resolve the user via their email
            var user = await _userManager.FindByEmailAsync(model.Email);
            // Get the roles for the user
            var roles = await _userManager.GetRolesAsync(user);

            // Do something with the roles here
        }
        else
        {
            // Uh oh....
        }
    }

    // Something is probably wrong, provide the form again....
    return View(model);
}
like image 186
Rion Williams Avatar answered Oct 14 '22 02:10

Rion Williams


Short but useful:

[Route("api/[controller]")]
[ApiController]
public class RoleController : ControllerBase
{
    private readonly UserManager<User> userManager;

    public RoleController(
        UserManager<User> userManager
        )
    {
        this.userManager = userManager;
    }

    // GET api/role
    [HttpGet]
    [Authorize]
    public async Task<IEnumerable<string>> Get()
    {
        var userId = User.FindFirstValue(ClaimTypes.Name);
        var user = await userManager.FindByIdAsync(userId);
        var role = await userManager.GetRolesAsync(user);
        return role;
    }
}

Hopes it helps.

like image 40
ConductedClever Avatar answered Oct 14 '22 02:10

ConductedClever