MVC 5 - Roles - IsUserInRole and Adding user to role

Leandro Soares picture Leandro Soares · Sep 9, 2014 · Viewed 10.1k times · Source

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?).

Answer

Marco picture Marco · Sep 9, 2014

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