Creating Roles in Asp.net Identity MVC 5

C#asp.net Mvc-5asp.net Identity

C# Problem Overview


There is very little documentation about using the new Asp.net Identity Security Framework.

I have pieced together what I could to try and create a new Role and add a User to it. I tried the following: https://stackoverflow.com/questions/19541101/add-role-in-asp-net-identity

which looks like it may have gotten the info from this blog: building a simple to-do application with asp.net identity and associating users with to-does

I have added the code to a Database Initializer that is run whenever the model changes. It fails on the RoleExists function with the following error:

> System.InvalidOperationException occurred in mscorlib.dll The entity type IdentityRole is not part of the model for the current context.

protected override void Seed (MyContext context)
{
    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
    var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

    // Create Admin Role
    string roleName = "Admins";
    IdentityResult roleResult;

    // Check to see if Role Exists, if not create it
    if (!RoleManager.RoleExists(roleName))
    {
        roleResult = RoleManager.Create(new IdentityRole(roleName));
    }
}

Any help is appreciated.

C# Solutions


Solution 1 - C#

Here we go:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    
    
   if(!roleManager.RoleExists("ROLE NAME"))
   {
      var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
      role.Name = "ROLE NAME";
      roleManager.Create(role);

    }

Solution 2 - C#

Verify you have following signature of your MyContext class

public class MyContext : IdentityDbContext<MyUser>

Or

public class MyContext : IdentityDbContext

The code is working for me, without any modification!!!

Solution 3 - C#

Here is the complete article describing how to create roles, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains the User interface, controller methods, etc.

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Solution 4 - C#

In ASP.NET 5 rc1-final, I did following:

Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
	public ApplicationRoleManager(
		IRoleStore<IdentityRole> store,
		IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
		ILookupNormalizer keyNormalizer,
		IdentityErrorDescriber errors,
		ILogger<RoleManager<IdentityRole>> logger,
		IHttpContextAccessor contextAccessor)
		: base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
	{
	}
}

To ConfigureServices in Startup.cs, I added it as RoleManager

services.
    .AddIdentity<ApplicationUser, IdentityRole>()
	.AddRoleManager<ApplicationRoleManager>();
		

For creating new Roles, call from Configure following:

public static class RoleHelper
{
	private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
	{
		if (!await roleManager.RoleExistsAsync(roleName))
		{
			await roleManager.CreateAsync(new IdentityRole(roleName));
		}
	}
	public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
	{
		// add all roles, that should be in database, here
		await EnsureRoleCreated(roleManager, "Developer");
	}
}

public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
     ...
     await roleManager.EnsureRolesCreated();
     ...
}

Now, the rules can be assigned to user

await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");

Or used in Authorize attribute

[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}

Solution 5 - C#

As an improvement on Peters code above you can use this:

   var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
        
   if (!roleManager.RoleExists("Member"))
            roleManager.Create(new IdentityRole("Member"));

Solution 6 - C#

My application was hanging on startup when I used Peter Stulinski & Dave Gordon's code samples with EF 6.0. I changed:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

to

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));

Which makes sense when in the seed method you don't want instantiate another instance of the ApplicationDBContext. This might have been compounded by the fact that I had Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); in the constructor of ApplicationDbContext

Solution 7 - C#

Roles View Model

public class RoleViewModel
{
    public string Id { get; set; }
    [Required(AllowEmptyStrings = false)]
    [Display(Name = "RoleName")]
    public string Name { get; set; }
}

Controller method

    [HttpPost]
    public async Task<ActionResult> Create(RoleViewModel roleViewModel)
    {
       if (ModelState.IsValid)
       {
           var role = new IdentityRole(roleViewModel.Name);
           var roleresult = await RoleManager.CreateAsync(role);
           if (!roleresult.Succeeded)
           {
               ModelState.AddModelError("", roleresult.Errors.First());
               return View();
           }
           return RedirectToAction("some_action");
       }
       return View();
    }

Solution 8 - C#

I wanted to share another solution for adding roles:

<h2>Create Role</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
    @Html.TextBox("RoleName", null, new { @class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}

Controller:

    [HttpGet]
    public ActionResult AdminView()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AdminView(FormCollection collection)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        if (roleManager.RoleExists(collection["RoleName"]) == false)
        {
            Guid guid = Guid.NewGuid();
            roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
        }
        return View();
    }

Solution 9 - C#

If you are using the default template that is created when you select a new ASP.net Web application and selected Individual User accounts as Authentication and trying to create users with Roles so here is the solution. In the Account Controller's Register method which is called using [HttpPost], add the following lines in if condition.

> using Microsoft.AspNet.Identity.EntityFramework;

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)
{
  var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
  var roleManager = new RoleManager<IdentityRole>(roleStore);
  if(!await roleManager.RoleExistsAsync("YourRoleName"))
     await roleManager.CreateAsync(new IdentityRole("YourRoleName"));

  await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
  await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
  return RedirectToAction("Index", "Home");
}

This will create first create a role in your database and then add the newly created user to this role.

Solution 10 - C#

    public static void createUserRole(string roleName)
    {
        if (!System.Web.Security.Roles.RoleExists(roleName))
        {
            System.Web.Security.Roles.CreateRole(roleName);
        }
    }

Solution 11 - C#

the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.

string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                
                IdentityResult roleResult;
                foreach(var roleName in roleNames)
                {
                    if(!RoleManager.RoleExists(roleName))
                    {
                        roleResult = RoleManager.Create(new IdentityRole(roleName));
                    }
                }
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                UserManager.AddToRole("user", "role1");
                UserManager.AddToRole("user", "role2");
                context.SaveChanges();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncolbyJaxView Question on Stackoverflow
Solution 1 - C#Piotr StulinskiView Answer on Stackoverflow
Solution 2 - C#jd4uView Answer on Stackoverflow
Solution 3 - C#Sheo NarayanView Answer on Stackoverflow
Solution 4 - C#nothrowView Answer on Stackoverflow
Solution 5 - C#Dave GordonView Answer on Stackoverflow
Solution 6 - C#Dane WView Answer on Stackoverflow
Solution 7 - C#MojiView Answer on Stackoverflow
Solution 8 - C#JoshYates1980View Answer on Stackoverflow
Solution 9 - C#Hamza KhanzadaView Answer on Stackoverflow
Solution 10 - C#Stephan AhlfView Answer on Stackoverflow
Solution 11 - C#KevinView Answer on Stackoverflow