在asp.net mvc中提供动态角色(角色不固定,不断更新)

Rus*_*hah 7 asp.net razor asp.net-mvc-3 asp.net-mvc-4 asp.net-mvc-5

我知道简单的角色提供者,如果我需要限制特定的操作,我必须简单地编写Authorize(Roles ="Admin")或者如果我需要限制视图的特定部分,我会写@if(User.IsInRole("管理员")).

但我的问题是,如果我的角色没有修复并存储在数据库中,我的超级管理员可以编辑和删除它们.

我的要求是superadmin可以添加,更新,删除角色,还可以创建不同的用户并维护这些用户的角色.

我做了很多谷歌搜索,发现如下内容

    [AttributeUsage (AttributeTargets.Method|AttributeTargets.Class,Inherited = true,AllowMultiple=true) ]
    public class CustomRole : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase context)
        {
            Respository db = new Respository();
            if (db.UserMasters.Where(x => x.user_name == context.User.Identity.Name).Count() > 0)
            {
                return true;
            }
            else { return false; }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我可以使用此代码来授权操作方法如下

    [CustomRole]
    public ActionResult Details(int id = 0)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        return View(employee);
    }
Run Code Online (Sandbox Code Playgroud)

这里我的这个动作方法受到保护,但如果我想通过这个自定义方法保护视图的某些部分该怎么办.如何使用此功能实现User.IsInRole("Admin")的功能?

ban*_*nny 5

您的要求将分三步完成

1- 创建所有默认角色,将其存储在数据库中。ie- roleid,rolename 2- 使用 roleid 创建新用户映射 userid 时。3-还为您必须授予的所有权限制作一张表格。4-为管理员制作单独的用户界面来更改每个用户的角色。数据库将如下图所示。 在此输入图像描述

ui将会是这样的。

在此输入图像描述

你自己试试这个..


Tie*_* T. 4

完全回答您的问题可能超出了 StackOverflow 的范围,因为它基本上需要为您编写大部分应用程序,但这是总体思路。

编写一个与此类似的辅助类:

public class ModuleHelper
{
    public static bool UserCanAccessModule(string moduleIdentifier)
    {
        bool canAccess = false;

        /* 
            Call into your service with current User.Name and module identifier (integer, GUID, whatever).
            Return result of whether user has the required role for the specified module
        */
        try
        {
            canAccess = service.CanUserAccessModule(User.Identity.Name, moduleIdentifier);
        }
        catch
        {
            // catching all exceptions, since this is a UI helper
        }       

        return canAccess;
    }

    // etcetera...
}
Run Code Online (Sandbox Code Playgroud)

我建议将其包装在应用程序的根命名空间中;否则,在文件夹中system.web.webPages.razor的 部分中添加对该类的命名空间的引用。然后,您可以执行以下操作:web.configViews

<div class="col-sm-3 col-md-2 sidebar">
    @if (ModuleHelper.UserCanAccessModule("moduleXYZ"))
    {
        @Html.Action("moduleXYZ")
    }
</div>
Run Code Online (Sandbox Code Playgroud)

这显然假设了很多,但这个想法在实践中并不新鲜或那么复杂。服务的逻辑比较简单:

  1. 查找用户
  2. 查找“操作”或“模块”
  3. 查找分配给每个角色的角色之间的交集(如果有)。

没有交集意味着用户不具有所需的角色。