基于用户权限的自定义身份验证和授权

Den*_*nis 12 c# authentication asp.net-mvc asp.net-identity

目前我正在开发一个带有MS Sql server数据库的ASP.Net MVC 5应用程序.我需要实现基于ASP.Net identity 2.0的身份验证和授权.我刚刚介绍了Identity的基本概念,并尝试在我的应用程序中实现相同的功能.由于数据库已经定义,我需要稍微自定义Identity.当我查看数据库时,表格与我通常在样本身份项目中发现的有点不同.

在此输入图像描述

从图像中可以看到,有一个名为user group的表,并根据模块定义了一组权限.默认情况下,用户可以访问相同的权限.如果要更改任何权限,可以通过在"用户权限"表中设置权限来覆盖它.

所以我的第一个问题是ASP.具有自定义授权和授权的网络身份是实现这样的场景的正确方法吗?

从视角来看,我必须根据用户/用户组权限生成菜单,并且还要根据它们启用/禁用按钮.我能够根据数据库值生成菜单.但我需要授权每个客户端请求,因此我认为AuthorizeAttribute是最佳选择.请指教?任何好的设计模式或帖子都很受欢迎.

Sam*_*ari 17

当然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();
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您只需将属性添加到操作中:

[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
}
Run Code Online (Sandbox Code Playgroud)

我省略了用户组以简化示例,并且我还编写了一些需要编写提供程序以从DB中获取的部分.