mercer
mercer

Reputation: 331

ASP.NET Identity 2.0 check if current user is in role IsInRole

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)
{
}

Upvotes: 22

Views: 43122

Answers (4)

Robert Goldwein
Robert Goldwein

Reputation: 6021

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)

Upvotes: 7

ookie
ookie

Reputation: 138

this worked for me hope this helps...

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

Upvotes: 3

bluee
bluee

Reputation: 1027

The correct way in ASP Identity is as simple as

User.IsInRole("rolename");

Upvotes: 41

Dougal
Dougal

Reputation: 61

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");

Upvotes: 6

Related Questions