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 ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.