Role Management in ASP MVC 5 (Microsoft.AspNet.Identity)
Solution 1
User.IsInRole
is basically looking at the claims for the currently signed in user. What does your sign in logic look like? That is what is responsible for minting the cookie that turns into the User identity. That needs to have the Role claim set properly for the IsInRole
method to work correctly.
Solution 2
I'm trying to understand how to use roles in MVC 5 myself, which is what brought me here. I can't answer your question, but check out this link. The downloaded solution works right out of the box and I've already been able to cut-and-paste some of the code and get it working in my own app. Now I'm trying to fully understand what it's doing.
It may not answer your question but at least it's a fully working solution that actually does work as described without a lot of hassle, so it's a good starting point.
Gordon2001
Updated on June 29, 2022Comments
-
Gordon2001 almost 2 years
in ASP MVC5 RC I didn't get the role system to work. My database has all needs tables an role exist but proofing if user is in role always return false (no SQL exception or something)!?
Did I need to activate role system for
IPrincipal
somewhere?Test code:
AccountController accCont = new AccountController(); // check role exist : result = true var roleExist = await accCont.IdentityManager.Roles.RoleExistsAsync("61c84919-72e2-4114-9520-83a3e5f09de1"); // try find role by name : result = role object var role = await accCont.IdentityManager.Roles.FindRoleByNameAsync("ProjectAdministrator"); // check with AccountController instance : result = true var exist = await accCont.IdentityManager.Roles.IsUserInRoleAsync(User.Identity.GetUserId(), role.Id); // check if current user is in role : result (both) = false???? var inRole = User.IsInRole(role.Id); var inRole2 = User.IsInRole(role.Name);
I also try to build an custom extenuation like the
IIdentity.GetUserId()
extension method fromMicrosoft.AspNet.Identity.Owin
Namespace.namespace Microsoft.AspNet.Identity { public static class IdentityExtensions { public static string IsUserInRole(this IIdentity identity) { if (identity == null) { throw new ArgumentNullException("identity"); } ClaimsIdentity identity2 = identity as ClaimsIdentity; if (identity2 != null) { var result = identity2.FindFirstValue(IdentityConfig.Settings.GetAuthenticationOptions().RoleClaimType); return null; // later result } return null; } } }
But the result for claim Type
RoleClaimType
is alwaysnull
:( I'm really stuck with this.Thank you for your help! Steffen
-
janhartmann over 10 yearsI need this as well!!
-
taher chhabrawala over 10 years@JeremyCook did you get the solution. I have implemented a custom user store instead of using the default entity framework one. the roles related methods do not get call when [Authorize(Roles = "Admin")] is executed
-
Jeremy Cook over 10 yearsI did find the source of my problem and posted the answer here.