Home > Enterprise >  Find User Role ASP.Net Core
Find User Role ASP.Net Core

Time:03-17

Trying to find out where roles are assigned to a particular user in an ASP.Net core app. I'm new to .net core so bare with me. I can debug and see the username and password but cannot figure out where the roles are set for this particular user? If there's something else I need to add here please advise.

I use the login provide and get "No roles assigned." below for the user. I have in the Login.cshtml.cs page:

                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");

                    var user = _signInManager.UserManager.Users.Where(a => a.Email == Input.Email).FirstOrDefault();

                    if (user == null || !user.IsActive)
                    {
                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return Page();
                    }
                    else
                    {
                        var roles = await _userManager.GetRolesAsync(user);

                        if (!roles.Any())
                        {
                            ModelState.AddModelError(string.Empty, "No roles assigned.");
                            return Page();
                        }

                        if ((returnUrl ?? "").Length < 1)
                        {
                            returnUrl = await GetRoleHomepage(user);
                        }
                    }

                    return RedirectToPage(returnUrl);
                }

Honestly, I'm used to website's, the old school pages because I'm coming from local government which is far behind private. Now I'm private and now stressed. Looking at the AccountController.cs I see:

    [Route("[controller]/[action]")]
    public class AccountController : Controller
    {
        private readonly SignInManager<AspNetUsers> _signInManager;
        private readonly ILogger _logger;

        public AccountController(SignInManager<AspNetUsers> signInManager, ILogger<AccountController> logger)
        {
            _signInManager = signInManager;
            _logger = logger;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            _logger.LogInformation("User logged out.");
            return RedirectToPage("/Index");
        }
    }

Thanks for the input: The only part I see with IdentityRole is in a class with this but it's empty:

using Microsoft.AspNetCore.Identity;

namespace Portal.HPAG.Data
{
    public partial class AspNetRoles : IdentityRole
    {
    }
}

And then I found a AspNetRoles class:

using System;
using System.Collections.Generic;

namespace Portal.HPAG.Data
{
    public partial class AspNetRoles
    {
        public AspNetRoles()
        {
            AspNetUserRoles = new HashSet<AspNetUserRoles>();
            PartStatusTypeRoles = new HashSet<PartStatusTypeRoles>();
            RoleLevels = new HashSet<RoleLevels>();
            Stage = new HashSet<Stage>();
        }

        public string Id { get; set; }
        public bool IsManager { get; set; }

        public virtual ICollection<AspNetUserRoles> AspNetUserRoles { get; set; }
        public virtual ICollection<PartStatusTypeRoles> PartStatusTypeRoles { get; set; }
        public virtual ICollection<RoleLevels> RoleLevels { get; set; }
        public virtual ICollection<Stage> Stage { get; set; }
    }
}

Still digging through.

CodePudding user response:

In addition to AddToRoleAsync(TUser user, string role) and IsInRoleAsync, you should be able to iterating through roles in an IEnumerable<IdentityRole> variable.

You should be able to set a new variable for _roleManager using:

serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

CodePudding user response:

You can learn how to use UserManager and RoleManager to manager your user and role. There are many methods encapsulated in Them. You can use UserManager and RoleManager via dependency injection like signInManager.

I list a few very common methods below:

Add role in user: userManager.AddToRoleAsync(user, role.Name);

Add the specified user to the named roles: userManager.AddToRolesAsync(user, IEnumerable<role.Name>)

Returns a list of users from the user store who are members of the specified roleName: userManager.GetUsersInRoleAsync(role.Name)

Returns a flag indicating whether the specified user is a member of the given named role: userManager.IsInRoleAsync(user, role.Name)

There are other methods that I haven't listed, you can check them out through the hyperlinks I provided.

  • Related