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) { }
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.
var user = new ApplicationUser { UserName = model. Email, Email = model. Email }; var userRoles = await _userManager. GetRolesAsync(user);
The correct way in ASP Identity is as simple as
User.IsInRole("rolename");
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With