MVC 5 - Roles - IsUserInRole and Adding a User to a Role

In MVC4, I used Roles.IsUserInRole to check if a given user has any role. However, with MVC5 I can no longer do this ...

At first he asked to enable RoleManager in web.config, but then I found that microsoft had moved from Web.Security to Microsoft.AspNet.Identity.

Now my question is: with Microsoft.AspNet.Identity, how can I do an action like Roles.IsUserInRole? And / or create a relationship between the Role and the User.

By the way, I'm still trying to understand the new authentication methods (ClaimsIdentity?).

+5
source share
2 answers

You should read http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx for the basics of Identity 2.0!

There is also a full demo project to get you started: https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys

If you take this as the basis for your Identity foundation, you will get something like this:

var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); const string name = "YourUsername" const string roleName = "Admin"; var user = userManager.FindByName(name); //check for user roles var rolesForUser = userManager.GetRoles(user.Id); //if user is not in role, add him to it if (!rolesForUser.Contains(role.Name)) { userManager.AddToRole(user.Id, role.Name); } 
+10
source

The post above was really helpful (Thanks Serv, vote if my reputation allowed me). This helped me solve the problem I was facing, with slight minor changes in line with what I was trying to achieve. My particular problem was that I wanted to check the appearance of MVC if the current user was in this role group. I also found that Roles.IsUserInRole no longer works.

If you do this in a view, but using the ASP.NET 2.0 identifier instead of the simple membership provider provided by previous versions of MVC, the following might be useful as a one-line solution:

 bool isAdmin = HttpContext.Current.User.IsInRole("Admin"); 

Then you can combine it with HTML to selectively display menu items (for which I used it):

 @if (isAdmin) { <li>@Html.ActionLink("Users", "List", "Account")</li> } 

This allows me to deny access to user management hyperlinks where the user is not a member of the "Admin" role.

+6
source

Source: https://habr.com/ru/post/1202141/


All Articles