Area level security for asp.net mvc

2019-01-23 06:36发布

问题:

I know it is possible to decorate a controller with the Authorize attribute to control access, what I don't know is the accepted or proper way to enforce security across all the controllers/views in an Area.

Is there something in web.config, area registration or some other place to apply authorization security?

回答1:

A convenient way is to create a new base class

[Authorize]
public abstract class AuthorizeBaseController :  Controller
{
}

and make sure that all of your controllers for which you require authorization (in your case, everything in the area that you're concerned about) descend from AuthorizeBaseController.

public class HomeController : AuthorizeBaseController
{
  public ActionResult Index()
  {
    return View();
  }
}

The [Authorize] attribute should affect all of the descendents of the new base class.

Edit The issue that I have with using the <location path="" > approach is that, since the routing engine makes it's possible for any route to call any controller, setting authorization based on the url (and thus a specific route) instead of the controller actions makes it possible to call a controller that should be protected and skip the authorization. That wasn't an issue in webforms since a page was a page (and not a method call), but the separation between page/path and code in MVC makes this a huge security hole.



回答2:

The only safe way of doing this in an MVC application is to do what David suggests - attributing a base controller and having all controllers in the area subclass that base controller.

Using a <location> tag for authorization in MVC will open security holes in your application. You're not interested in securing URLs or routes. You want to secure the controllers themselves, since they're the actual resources you're trying to protect. Therefore the protections need to be placed directly on the controllers.

Furthermore, remember that an area is really just a fancy way of grouping routes, not controllers. Trying to use fancy logic to detect the current area and infer authorization settings will also open security holes in your application.



回答3:

As was already suggested, you can make use of the <location /> element in your web.config. Otherwise, you can use a base controller class per-area and decorate that with the AuthorizeAttribute so that all controllers which inherit from it are also filtered.



回答4:

you can always use <location path="" > <system.web> <authorization> deny or allow </authorization> </system.web> </location>