Using the Authorize Attribute to Require Role Membership
So far you've looked at the use of the AuthorizeAttribute to prevent anonymous access to a controller or controller action. However, as mentioned, you can also limit access to specific users or roles as well. A common example of where this is used is in administrative functions. After some work, your Music Store application has grown to the point that you're no longer happy with editing the album catalog by directly editing the database. It's time for a StoreManagerController.
However, this StoreManagerController can't just allow any random registered user who just opened an account to buy an album. You need the ability to limit access to specific roles or users. Fortunately, the AuthorizeAttribute allows you to specify both roles and users as shown here:
[Authorize(Roles="Administrator")] public class StoreManagerController : Controller
This will restrict access to the StoreManagerController to users who belong to the Administrator role. Anonymous users, or registered users who are not members of the Administrator role, will be prevented from accessing any of the actions in the StoreManagerController.
As implied by the name, the Roles parameter can take more than one role. You can pass in a comma-delimited list:
[Authorize(Roles="Administrator,SuperAdmin")] public class TopSecretController:Controller
You can also authorize by a list of users:
[Authorize(Users="Jon,Phil,Scott,Brad")] public class TopSecretController:Controller
And you can combine them as well:
[Authorize(Roles="UsersNamedScott", Users="Jon,Phil,Brad")] public class TopSecretController:Controller
When and How to Use Roles and Users
It's generally considered a better idea to manage your permissions based on roles instead of users, for several reasons:
When you're creating role groups, consider using privileged-based role groups. For example, roles named CanAdjustCompensation and CanEditAlbums are more granular and ultimately more manageable than overly generic groups like Administrator followed by the inevitable SuperAdmin and the equally inevitable SuperSuperAdmin.
For a full example of the interaction between the security access levels discussed, download the MVC Music Store application from http://mvcmusicstore.codeplex.com and observe the transition between the StoreController, CheckoutController, and StoreManagerController. This interaction requires several controllers and a backing database, so it's simplest to download the completed application code rather than to install a NuGet package and walk through a long list of configuration steps.