Search code examples
asp.net-web-apirolesasp.net-identity

How to create roles and add users to roles in ASP.NET MVC Web API


I have a .NET Web API project that users the individual accounts. I can register users fine using the standard template AccountController. However, I now want to set up roles and add users to roles depending on the type of user.

There are no roles automatically set up in the DB. How do I set up the roles and how do I add users to the roles?

The only information I can find on this is based on the old ASP.NET Membership, so it fails on the fact that the stored procedures are not set up for it.

Have scoured forums and tutorials on MSDN and can't seem to find an example for Web API.


Solution

  • You can add roles using the RoleManager...

    using (var context = new ApplicationDbContext())
    {
        var roleStore = new RoleStore<IdentityRole>(context);
        var roleManager = new RoleManager<IdentityRole>(roleStore);
    
        await roleManager.CreateAsync(new IdentityRole { Name = "Administrator" });
    
        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
    
        var user = new ApplicationUser { UserName = "admin" };
        await userManager.CreateAsync(user);
        await userManager.AddToRoleAsync(user.Id, "Administrator");
    }
    

    You're right that documentation is a bit light right now. But I find that once you've worked with the RoleManager and the UserManager a bit, the API's are pretty discoverable (but perhaps not always intuitive and sometimes you have to run queries directly against the store or even the db context).