ASP MVC Authorize all actions except a few

前端 未结 7 625
逝去的感伤
逝去的感伤 2020-12-13 00:29

I have a controller and I would like to require Authorization for all actions by default except a couple. So in the example below all actions should require authentication e

相关标签:
7条回答
  • 2020-12-13 01:33

    Here's what I would do, similar to Craig's answer with a couple of changes:

    1) Create an ordinary attribute deriving from System.Attribute (no need to derive from FilterAttribute since you aren't going to be using anything FilterAttribute provides).

    Maybe create a class hierarchy of attributes so you can test based on the hierarchy, e.g.

    Attribute
        AuthorizationAttribute
             AuthorizationNotRequiredAttribute
             AuthorizationAdminUserRequiredAttribute
                 AuthorizationSuperUserRequiredAttribute
    

    2) In your BaseController override the OnAuthorization method rather than the OnActionExecuting method:

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        var authorizationAttributes = filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AuthorizationAttribute>();
        bool accountRequired = !authorizationAttributes.Any(aa => aa is AuthorizationNotRequiredAttribute);
    

    I like the approach of being secure by default: even if you forget to put an attribute on the Action it will at least require a user to be logged in.

    0 讨论(0)
提交回复
热议问题