开发者

get current user's role

开发者 https://www.devze.com 2022-12-16 23:12 出处:网络
Is there any way to get the explicit role that a user belongs to in my controller? This assumes using ASP.NET Membership a开发者_JS百科nd Role Providers. \"IsInRole\" doesn\'t work - I need to actuall

Is there any way to get the explicit role that a user belongs to in my controller? This assumes using ASP.NET Membership a开发者_JS百科nd Role Providers. "IsInRole" doesn't work - I need to actually get the name of the role they are in.


A user can be in more than one role so you can't get the one role that the user is in, but you can easily get the list of roles a user is in.

You can use the Roles type to get the list of roles that the currently logged in user is in:

public ActionResult ShowUserRoles() {
    string[] roleNames = Roles.GetRolesForUser();
    return View(roleNames);
}

Or if you want to get the roles for an arbitrary user you can pass in the username when you call Roles.GetRolesForUser().


You can get a list of Roles from the GetRoles method. (From the link)

  string[] rolesArray;

  public void Page_Load()
  {
       RolePrincipal r = (RolePrincipal)User;
       rolesArray = r.GetRoles();
       ...//extra code
  }


Simplemembership in MVC4:

Getting the User's role-

var role = System.Web.Security.Roles.GetRolesForUser().Single();

To check if the user belongs to a certain role-

if (User.IsInRole("External"))


You can get the current user's role with Roles.GetRolesForUser().

To check if a user belongs to a role here is what I did:

Roles.GetRolesForUser().Contains("Administrator")


I don't know if I'm missing some weird setting or setup, but I cannot get e.g. User.IsInRole or Roles.GetRolesForUser() to work. I just get an exception (I think null reference), and the application just halts. Even though I have configured a RoleManager to the OwinContext and a Create method etc. like in the Identity Sample project by Microsoft, as well as enabled Role Manager in web.config. I solved this at first using another approach, like this (db is the ApplicationDbContext):

var UserID = User.Identity.GetUserId();    
var userRoles = db.Roles.Include(r => r.Users).ToList();

var userRoleNames = (from r in userRoles
                            from u in r.Users
                            where u.UserId == UserID
                            select r.Name).ToList();

This may not be the most optimized way and can possibly be altered to a simplier form but it worked for me and may not require as much setup/dependencies as other approaches. The second approach is this (add this to your controller class):

    private ApplicationDbContext db = new ApplicationDbContext();
    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        set
        {
            _userManager = value;
        }
    }

    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

Inside your controller you can now do e.g.:

var UserID = User.Identity.GetUserId();
var RolesForUser = await UserManager.GetRolesAsync(UserID);

I'm using ASP.NET MVC 5 application just to be clear. The RoleManager isn't used in this example but it can be used for creating, finding, updating etc. roles. Using this approach allows for async calls using await, in case that is a benefit for your application.


I Use this code

 ((ClaimsIdentity)User.Identity).FindAll(ClaimTypes.Role).ToList()
 .OrderBy(x => x.Value == "admin" ? 1
 : x.Value == "Salesperson" ? 2 
 : x.Value == "User" ? 3 : 4).First().Value


if you want to get the role name of any user, then simply use following two functions in the controller you want to perform action .

public ApplicationSignInManager SignInManager
        {
            get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); }
            private set { _signInManager = value; }
        }

        public ApplicationUserManager UserManager
        {
            get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
            private set { _userManager = value; }
        }

and then in the action , use the following line .

var role = UserManager.GetRoles(UserId);

note that here UserId is the id of ApplicationUser.

this role will be IList

if your application logic is such that a user can be in only one role then you can access it by

string roleName = role[0];


well i'm using .net 6 and i was going to use the UserManager in an custom Attribute but non of the answers helped me

At the end I ended up creating an service and interface and sum it up using dependency injection

my interface "IPermisisonAuthorization" :

public interface IPermissionAuthorization
{
    public List<IdentityUser> GetAllRoles(string id);
}

in my service "PermissionAuthorization" :

public class PermisisonAutorization : IPermissionAuthorization
{
    UserManager<IdentityUser> userManager;

    public PermisisonAutorization(UserManager<IdentityUser> userManager)
    {
        this.userManager = userManager;
    }

    public List<IdentityUser> GetAllRoles(string id) {
        return userManager.Users.Where(user => user.Id == id).ToList();
    }
}

in Program.cs :

builder.Services.AddTransient<IPermissionAuthorization, PermisisonAutorization>();

and in your class you can get it by HttpContext :

IPermissionAuthorization permissionAuthorization = context.HttpContext.RequestServices.GetService<IPermissionAuthorization>();

the "context" is of type "AuthorizationFilterContext" ant it should be passed by the controller, but custom attributes have them by default

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号