简体   繁体   English

自定义授权属性MVC

[英]Custom Authorize Attribute MVC

I'm looking for recommendations on how to have multiple authorize attributes on an action. 我正在寻找有关如何在一个动作上具有多个授权属性的建议。

eg: 例如:

[AuthorizePermission(PermissionName.SectionOne, PermissionLevel.Two)]
[AuthorizePermission(PermissionName.SectionTwo, PermissionLevel.Three)]
public ActionResult Index(int userId = 0){

}

If the user has access to SectionOne OR SectionTwo with the required PermissionLevel then they should be allowed in. 如果用户可以使用所需的PermissionLevel访问SectionOne或SectionTwo,则应允许他们进入。

The problem i'm facing is how do I check both attributes before deciding they aren't allowed in (as they are separate attributes)? 我面临的问题是,在确定不允许使用这两个属性之前,应如何检查它们(因为它们是单独的属性)? If the first one fails then it will never get to the second one. 如果第一个失败,那么它将永远不会到达第二个。

I can not pass both permission sets to one attribute as they need to be paired together. 我不能将两个权限集都传递给一个属性,因为它们需要配对。

Does anyone have any suggestions? 有没有人有什么建议?

I can not pass both permission sets to one attribute as they need to be paired together. 我不能将两个权限集都传递给一个属性,因为它们需要配对。

Yes, you can. 是的你可以。

There is no reason why you can't include all the permissions in a single attribute. 没有理由不能将所有权限都包含在一个属性中。 Something like this: 像这样:

[AuthorizePermission(new Permission[]{
   new Permission(PermissionName.SectionOne, PermissionLevel.Two), 
   new Permission(PermissionName.SectionTwo, PermissionLevel.Three)}]

This would pass an array of Permission objects, which you can then evaluate in your method with OR logic. 这将传递一个Permission对象数组,然后可以使用OR逻辑在您的方法中对其进行求值。

public class AuthorizePermissionAttribute : AuthorizeAttribute
{
    private Permission[] _permissions = null;
    public AuthorizePermissionAttribute(Permission[] permissions)
    {
        _permissions = permissions;
    }
}

You could even get fancy and add a parameter that tells whether to AND or OR them... 您甚至可以花哨并添加一个参数来告诉他们是AND还是OR ...

The only way that I know is something like this 我知道的唯一方法就是这样

 public class CustomRolesAttribute : AuthorizeAttribute
  {
     public CustomRolesAttribute(params string[] roles)
     {
       Roles = String.Join(",", roles);
     }
  }

Usage: 用法:

[CustomRoles("members", "admin")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM