Roles management in ASP.NET Identity

Introduction


Roles are a collections of users, for example, "Admin", "Developer", "Manager", that are usually used in an application in order to give permission or restrict access for a certain set of features.

We have seen in the ASP.NET Identity Architecture section that all role-related operations are performed by a Role manager. In this section, i'm going to show you how to configure and use this role manager.

Role manager


Go to App_Start > IdentityConfig.cs and create a new ApplicationRoleManager class as follows :

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) 
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<Context>()));

        return manager;
    }
}

The ApplicationRoleManager class extends the generic RoleManager class and supplies to it the type argument IdentityRole. The class contains a constructor that calls the base constructor of the RoleManager class and passes the IRoleStore<IdentityRole, string> object to it as an argument.

The class contains also the static method Create that creates and returns a new instance of the ApplicationRoleManager class.

In order to use the ApplicationRoleManager class in our application, go to App_Start > Startup.Auth.cs and add the following line in the ConfigureAuth method :

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

The preceding code registers the ApplicationRoleManager.Create callback that will be invoked to create and store an instance of ApplicationRoleManager in the OwinContext so it can be fetched upon request.

Usage


We can use the created application role manager by calling the Get method on the OwinContext.

public class RoleController : Controller
{
    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); 
        }

        private set
        {
            _roleManager = value;
        }
    }
}

In preceding code, we've created a role controller that contains an application role manager property. We get the ApplicationRoleManager object from the OWIN context by using the Get method and we store it in the role manager property.

Now, we can use the role manager property in our controller to perform a role-related operation.

use the application role manager

Namespace


In order to use the Get method, you have to include the following namespace :

using Microsoft.AspNet.Identity.Owin;