Authorize attribute vs authorization node in web.c

2019-01-15 13:50发布

问题:

I know I can restrict the access to an ASP.NET MVC 3 application using the authorization tag in web.config

   <authentication mode="Windows"></authentication>
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
    <authorization>
      <allow roles="MyDomain\MyGroup" />
      <deny users="*" />
      <deny users="?" />
    </authorization>

or decorating the controller base class with an [Authorize()] attribute (or even with a custom Authorize attribute)

[AdminOnly]
public class BaseController : Controller{}

The question is: are they alternative and equivalent approaches? Should I always use one approach rather than the other? Which elements should I keep in mind?

回答1:

I know I can restrict the access to an ASP.NET MVC 3 application using the authorization tag in web.config

No, don't use this in ASP.NET MVC.

The question is: are they alternative and equivalent approaches?

No, they are not alternative. You should not use the <authorization> tag in web.config in an ASP.NET MVC application because it is based on paths, whereas MVC works with controller actions and routes. The correct way to do authorization in ASP.NET MVC is using the [Authorize] attribute.