5

In MVC4 i used Roles.IsUserInRole to check if a given user is in some role. However, with MVC5 i can't do it anymore...

At first, it asked me to enable RoleManager at the web.config but then i discovered that microsoft moved away from Web.Security to Microsoft.AspNet.Identity.

My question now is, with Microsoft.AspNet.Identity how do i do an action similar to Roles.IsUserInRole? And/or create a relation between the Role and the User.

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

Leandro Soares
  • 2,902
  • 2
  • 27
  • 39

2 Answers2

11

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's also a complete 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'll end up with 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);
}
Marco
  • 22,856
  • 9
  • 75
  • 124
  • Ok, it worked... thanks. By the way, the authorize attribute isn't working... any ideia? i can't read the article right now, but i will read it from top to bottom asap. – Leandro Soares Sep 09 '14 at 10:59
  • 1
    I suggest you ask another question with an adequate description for this problem, because all I would do here is guessing. – Marco Sep 09 '14 at 11:00
  • ok thanks i created the post http://stackoverflow.com/questions/25743113/mvc-5-roles-authorizeattribute-outdated – Leandro Soares Sep 09 '14 at 11:09
7

The post above was really helpful (Thanks Serv, would vote up if my reputation allowed me to). It helped me solve an issue I was having with a few minor changes to fit what I was trying to achieve. My particular problem was that I wanted to check in an MVC view if the current user was in a given role group. I also found that Roles.IsUserInRole was no longer working.

If you are doing this in a view, but using ASP.NET identity 2.0 instead of the simple membership provider offered by previous MVC versions, the following might be helpful as a 1-line solution:

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

You may then combine it with HTML to selectively show menu items (which is what I've been using it for) with something like this:

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

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

RichL
  • 183
  • 1
  • 10