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

标签 c# asp.net-mvc authentication asp.net-identity

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

enter image description here

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

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

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

最佳答案

当然 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);
    }
}

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

[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
}

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

关于c# - 基于用户权限的自定义认证和授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29988858/

相关文章:

asp.net-mvc - 将文件夹中的所有文件包含在一个包中

javascript - 使用 JavaScript 客户端的 SignalR 身份验证

security - apache 的密码文件放在哪里?

c# - .NET : Is creating new EventArgs every time the event fires a good practice?

c# - 透明Windows窗体,内部有OpenGL绘图

c# - 为什么此递归不产生 StackOverFlowException?

c# - 在 Blazor 中的 View 之外访问经过身份验证的用户

c# - ASP.NET 用户控件 : can't initialize a user control property using Eval ("...")

HTML.TextAreaFor - 删除仅供显示的 html 标签

c# - 在资源文件中存储 html 标签的最佳实践/技巧