基于用户权限的自定义认证和授权

Custom authentication and authorization based on user rights

目前我正在使用 MS Sql 服务器数据库开发 ASP.Net MVC 5 应用程序。我需要基于ASP.Net identity 2.0实现认证授权。我刚刚了解了 Identity 的基本概念,并尝试在我的应用程序中实现相同的概念。由于已经定义了数据库,因此我需要稍微自定义一下 Identity。当我查看数据库时,tables 与我通常在样本身份项目中发现的有点不同。

从图中您可以看到有一个名为 用户组 的 table 和基于模块定义的一组权限。默认情况下,用户将可以访问相同的权限。如果您想更改任何权限,您可以通过在用户权限 table.

中设置权限来覆盖它

所以我的第一个问题是,ASP。 Net Identity with Custom Authorization and Authorization 是实现这种场景的正确方法吗?

从视图的角度来看,我必须根据用户/用户组权限生成菜单,并且还想根据它们启用/禁用按钮。我能够根据数据库值生成菜单。但我需要授权每个客户端请求,为此我认为 AuthorizeAttribute 是最佳选择。请建议?任何好的设计模式或 post 都会受到赞赏。

当然 Identity 如此强大和灵活,您可以自定义它。使用您的用户权利作为声明,然后编写自定义 AuthorizeAttribute 来检查声明,例如考虑此代码:

[HttpPost]
public ActionResult Login(string username, string password)
{
    if (_userManager.IsValid(username, password)) // your own user manager 
    {
        var ident = new ClaimsIdentity(
          new[] 
          {
              // adding following 2 claim just for supporting default antiforgery provider
              new Claim(ClaimTypes.NameIdentifier, username),
              new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

              new Claim(ClaimTypes.Name, username),
              // populate assigned user rightID's form the DB and add each one as a claim  
              new Claim("UserRight","FirstAssignedUserRightID"),
              new Claim("UserRight","SecondAssignedUserRightID"),
          },
          DefaultAuthenticationTypes.ApplicationCookie);

        HttpContext.GetOwinContext().Authentication.SignIn(
           new AuthenticationProperties { IsPersistent = false }, ident);
        return RedirectToAction("MyAction"); // auth succeed 
    }
    // invalid username or password
    ModelState.AddModelError("", "invalid username or password");
    return View();
}

并编写基于声明的授权属性:

public class ClaimsAccessAttribute : AuthorizeAttribute 
{
    // in the real world you could get claim value form the DB, 
    // I simplified the example 
    public string ClaimType { get; set; }
    public string Value { get; set; }

    protected override bool AuthorizeCore(HttpContextBase context) 
    {
        return context.User.Identity.IsAuthenticated
            && context.User.Identity is ClaimsIdentity
            && ((ClaimsIdentity)context.User.Identity).HasClaim(x =>
                x.Type == ClaimType && x.Value == Value);
    }
}

最后你只需要将你的属性添加到你的动作中:

[ClaimsAccess(CliamType="UserRight",Value="YourRightID"]
public ActionResult MyAction()
{
    // also you have access the authenticated user's claims 
    // simply by casting User.Identity to ClaimsIdentity
    // ((ClaimsIdentity)User.Identity).Claims
}

我省略了用户组以简化示例,并且我还硬编码了一些您需要编写提供程序以从数据库中获取的部分。