Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) { } 
like image 799
mercer Avatar asked Apr 13 '14 23:04

mercer


People also ask

How do you get user role in identity?

it gives you the AspNetUserInRoles which stores UserId and RoleId. Instead you could try UserManger 's GetRoles method which will return you List<string> of roles user is assigned. But as you mentioned it will be only one role hence you can take first value from the result of GetRoles method.

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


2 Answers

The correct way in ASP Identity is as simple as

User.IsInRole("rolename"); 
like image 140
bluee Avatar answered Oct 07 '22 18:10

bluee


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)

like image 23
Robert Goldwein Avatar answered Oct 07 '22 16:10

Robert Goldwein