Role-based authorization in ASP.NET Identity

Introduction


We've seen in the Authorization section, how to restrict access to resources for non-authenticated users.

In this section, i'm going to show you how to restrict access to resources for authenticated users based on their roles.

Authorization


Let's suppose we have the following account controller :

[Authorize]
public class AccountController : Controller
{
    public ActionResult EnableAccount(string userId)
    {
        // Implementation ...
        return View();
    }

    public ActionResult DisableAccount(string userId)
    {
        // Implementation ...
        return View();
    }
}

We've used the Authorize attribute on the controller to specify that access is restricted to authenticated users. This limitation is not enough in this use case because we don't want any user to be able to disable or enable user accounts. For example, only users that have an Admin role should have the right to access these features.

In order to do that, we can use the Roles property of the Authorize attribute :

[Authorize(Roles = "Admin")]
public class AccountController : Controller
{
    public ActionResult EnableAccount(string userId)
    {
        // Implementation ...
        return View();
    }

    public ActionResult DisableAccount(string userId)
    {
        // Implementation ...
        return View();
    }
}

This way, only users who are members of the Admin role can have access to the account controller.

We can also specify multiple roles as a comma seperated list :

[Authorize(Roles = "Admin, Manager")]
public class AccountController : Controller
{
    public ActionResult EnableAccount(string userId)
    {
        // Implementation ...
        return View();
    }

    public ActionResult DisableAccount(string userId)
    {
        // Implementation ...
        return View();
    }
}

This way, the account controller will only be accessible to users who are members of either the Admin role or the Manager role.

If you apply multiple Authorize attributes instead of the comma seperated list, then the users must be members of all roles in order to access the controller.

[Authorize(Roles = "Admin")]
[Authorize(Roles = "Manager")]
public class AccountController : Controller
{
    public ActionResult EnableAccount(string userId)
    {
        // Implementation ...
        return View();
    }

    public ActionResult DisableAccount(string userId)
    {
        // Implementation ...
        return View();
    }
}

This way, the account controller will require users to be members of both the Admin role and the Manager role.