How to get custom annotation attributes for a controller action in ASP.NET MVC 4?

后端 未结 3 2023
花落未央
花落未央 2020-12-13 16:26

I am working with a permission based authorization system for my app in ASP.NET MVC. For this I have created a custom authorization attribute

public class M         


        
3条回答
  •  鱼传尺愫
    2020-12-13 16:50

    My only recommendation would be to write an extensions methods on IPrincipal instead which would look like

    public static bool HasRolesAndPermissions(this IPrincipal instance,
        string roles,
        string permissions,)
    {
      if(user not authenticated)
        return false;
    
      if(user has any role of Roles)
        return true;
    
      if(user has any permission of Permissions)
        return true;
    
    return false;
    }
    

    Then your code in the views/partials is a little more readable in terms of what it's actually doing (not doing anything with html, but validating a user) then the code in the views/partials looks like

    @if (User.HasRolesAndPermissions(roles, permissions)) 
    { 
       @Html.ActionLink(..);
    }
    

    Each MVC Page has the property WebViewPage.User for the current user.

    The problem with your purposed solution (and the link to security aware link) is that the creation of the link, and the Authorize on the controllers could be different (and mixing responsibilities in this type of fashion in MY opinion is bad practice). By extending IPrincipal a new authorization would look like:

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
      return user.HasRolesAndPermissions(roles, permissions)
    }
    

    Now both your Authorize Attribute and Views use the same roles/permissions data logic.

提交回复
热议问题