Search code examples
c#asp.netasp.net-identity

Initializing RoleManager in ASP.NET Identity with Custom Roles


I changed the primary key for the user database from string to int using the tutorial here, but I'm having difficulty initializing the Role Manager. It used to be initialized using

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

How can I create the role manager using the new data?

Update: I'm using MVC 5 and EF 6.


Solution

  • Your ApplicationRoleManager may look like this. because you have to inherit from your customRole class instead of IdentityRole.

    public class ApplicationRoleManager : RoleManager<CustomRole, int>
    {
        public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
            : base(roleStore)
        {
        }
    
        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            return new ApplicationRoleManager(new RoleStore<CustomRole, int, CustomUserRole>(context.Get<ApplicationDbContext>()));
        }
    }
    

    Then add following code to Startup.Auth.cs class if not currently exists.

    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    

    Then you create and manage roles.

        var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    
        const string roleName = "Admin";
    
        //Create Role Admin if it does not exist
        var role = roleManager.FindByName(roleName);
        if (role == null)
        {
            role = new CustomRole();
            role.Id = 1; // this will be integer
            role.Name = roleName;
    
            var roleresult = roleManager.Create(role);
        }
    

    Hope this helps.