c# - 自定义授权(权限)ASP.NET MVC

标签 c# asp.net-mvc authorization forms-authentication access-control

在我的应用程序中,一个角色有多个权限。我希望用户能够访问依赖于权限的操作,而不是角色。

假设:

  • Admin 有 perm1, perm2, perm3,
  • SuperAdmin 拥有 admin + perm4 和 perm5 的所有权限。
  • 此外,还有一些小伙子也拥有 perm1、perm3、perm6、perm7。

我想执行以下操作:我希望拥有 perm3 或 perm4 权限的人可以访问操作。这两个权限来自两个不同的角色。但是除了 perm3 Admin 有 perm1 和 perm2,拥有 perm3 的未成年人也可以访问此操作(不一定是管理员或 super 管理员)。

所以你明白我的意思了吧?我想在 ASP.NET MVC 4 中实现这一点。所以我想我需要制作自己的 AuthorizeAttribute、我自己的 IIdentity 并在 global.asax 中编写一些方法。在 ASP.NET 中还有一个成员资格,我需要触摸它吗?我不知道如何把所有的东西放在一起。谁能帮帮我?

最佳答案

public class PermissionAttribute : AuthorizeAttribute
    {
        private readonly IAccountService _accountService;
        private readonly IEnumerable<PermissionEnum> _permissions;

        public PermissionAttribute(params PermissionEnum[] permissions):
            this(DependencyResolver.Current.GetService<IAccountService>())
        {
            _permissions = permissions;
        }

        protected PermissionAttribute(IAccountService accountService)
        {
            _accountService = accountService;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if(!_permissions.Any(x=>_accountService.HasPermission(filterContext.HttpContext.User.Identity.Name,(int)x)))
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            base.OnAuthorization(filterContext);
        }

    }

关于c# - 自定义授权(权限)ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19512935/

相关文章:

c# - 有没有办法重用数据注释?

c# - 如何在 ASP.NET MVC Controller 中使用 Automapper 配置

ASP.NET 通过用户名授予目录访问权限

c# - 将 Unicode 数据从 xml 字符串插入到 Datatable

java - Java 的 NavigableMap.floorEntry、ceilingEntry 的 C Sharp 等价物

c# - 错误 XDG0008 : NumberBox is not supported in a Universal Windows Platform project

c# - System.IO.Directory.Exists() 与 Windows 和 Linux 一起使用

asp.net - 上下文菜单没有 "Add Scaffolding"和 "Add Controller"选项

ASP.NET 授权 * 和 ?意思是?

Angular:从 Spotify 请求访问 token 时出现 HTTP post 请求错误 "grant_type parameter is missing"