How can we set authorization for a whole area in ASP.NET MVC?

Abdulsattar Mohammed picture Abdulsattar Mohammed · Feb 23, 2010 · Viewed 35.8k times · Source

I've an Admin area and I want only Admins to enter the area. I considered adding the Authorized attribute to every controller in the Admin area. Isn't there an elegant solution or is this feature not there in the framework itself?

EDIT: I'm sorry, I should to have mentioned this before. I'm using a custom AuthorizedAttribute derived from AuthorizeAttribute.

Answer

Levi picture Levi · Feb 23, 2010

Web.config-based security should almost never be used in an MVC application. The reason for this is that multiple URLs can potentially hit a controller, and putting these checks in Web.config invariably misses something. Remember - controllers are not associated with areas, routes are associated with areas. The MVC controller factory will happily serve controllers from the Areas/ folder for non-area requests if there's no conflict.

For example, using the default project structure, adding an Admin area with an AdminDefaultController, you can hit this controller via /Admin/AdminDefault/Index and /AdminDefault/Index.

The only supported solution is to put your attribute on a controller base class and to ensure that each controller within the area subclasses that base class.