21

With ASP.NET Identity 2.0 how do you check if the currently logged on user is in a role? I am using the following, but wondering if there is something more efficient.

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DbContext()));
var au = um.FindByEmail(Context.User.Identity.GetUserName());
var inrole = um.IsInRole(au.Id, "Admin");

if (inrole)
{
}
User 12345678
  • 7,714
  • 2
  • 28
  • 46
mercer
  • 321
  • 1
  • 3
  • 12

4 Answers4

39

The correct way in ASP Identity is as simple as

User.IsInRole("rolename");
bluee
  • 997
  • 8
  • 18
  • 3
    It's worth noting that this only works if the user is logged in. – Stuart Dobson Jun 07 '15 at 09:29
  • 1
    What do you mean? The question is about the current logged in user. There is other ways to query about roles for a user who is not logged in – bluee Jun 08 '15 at 10:30
  • 2
    I suppose this way will check roles in ClaimsIdentity. For instance, if User1 is logged in and after that you will add User1 to Group1 User1.IsInRole("Group1") = false. User1 needs to logout-login. – mtkachenko Dec 14 '16 at 08:15
  • For this to work with JWT Authentication, you have to first add the roles in the ClaimsIdentity as mentioned in this post: https://stackoverflow.com/questions/42036810/asp-net-core-jwt-mapping-role-claims-to-claimsidentity – Scott Duncan Dec 20 '19 at 16:23
7

Assuming you are in ASP.NET, it's pretty simple:

if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
{
  return "You are not authorized to access this page.";
)

(from http://msdn.microsoft.com/en-us/library/4z6b5d42%28v=vs.110%29.aspx)

Bilzard
  • 371
  • 1
  • 5
  • 19
Robert Goldwein
  • 5,805
  • 6
  • 33
  • 38
6

You can get the user id from the Identity rather than having to lookup the user in the database...

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DbContext()));
var inrole = um.IsInRole(Context.User.Identity.GetUserId(), "Admin");
Dougal
  • 61
  • 1
  • 2
3

this worked for me hope this helps...

If HttpContext.Current.User.IsInRole("admin") Then
        adminmnu.Visible = True
    End If
ookie
  • 138
  • 11