【问题标题】:Role based security MVC & Mongodb基于角色的安全 MVC 和 Mongodb
【发布时间】:2017-11-29 07:43:22
【问题描述】:

我正在研究 asp.net mvc 应用程序和 mongodb 作为数据库。现在我想实现基于角色的安全性和权限。例如,我们有角色“用户”和“管理员”。现在,角色“user”的一个用户“A”有权查看页面,而其他用户说“B”可以查看和编辑页面内容,角色“admin”的用户可以拥有查看、编辑、添加的所有权限并删除。所以基本上我想要访问控制列表。请让我知道使用 mongodb 实现这一目标的最佳方法。

谢谢

【问题讨论】:

    标签: asp.net-mvc mongodb asp.net-identity asp.net-membership


    【解决方案1】:

    有很多步骤,所以我只能给你一个方向。

    最简单的方法是使用 OWIN Authentication Middle-ware,并将每个访问作为一个声明存储在 Principle Object 中,这样您就可以使用 ASP.Net 的 Authorize Attribute 构建。

    示例代码 -

    OWIN Authentication Middle-ware

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
    

    Store access as role claim in Principle object

    public void SignIn(User user, IList<string> roleNames)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Sid, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };
    
        foreach (string roleName in roleNames)
        {
            claims.Add(new Claim(ClaimTypes.Role, roleName));
        }
    
        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
    
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;
    
        authenticationManager.SignIn(identity);
    }
    

    用法

    [Authorize(Roles = "CanViewHome")]
    public class IndexController : Controller
    {
        [Authorize(Roles = "CanEditHome")]
        public ActionResult Edit()
        {
            return View();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      • 2013-03-21
      • 2011-05-12
      • 1970-01-01
      相关资源
      最近更新 更多