基于用户权限的自定义身份validation和授权
目前我正在开发一个带有MS Sql server数据库的ASP.Net MVC 5应用程序。 我需要实现基于ASP.Net identity 2.0的身份validation和授权。 我刚刚介绍了Identity的基本概念,并尝试在我的应用程序中实现相同的function。 由于数据库已经定义,我需要稍微自定义Identity。 当我查看数据库时,表格与我通常在样本身份项目中发现的有点不同。
从图像中可以看到,有一个名为user group的表,并根据模块定义了一组权限。 默认情况下,用户可以访问相同的权限。 如果要更改任何权限,可以通过在“用户权限”表中设置权限来覆盖它。
所以我的第一个问题是ASP。 具有自定义授权和授权的网络身份是实现这样的场景的正确方法吗?
从视角来看,我必须基于用户/用户组权限生成菜单,并且还希望基于它们启用/禁用按钮。 我能够根据数据库值生成菜单。 但我需要授权每个客户端请求,因此我认为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 }
我省略了用户组以简化示例,并且我还编写了一些需要编写提供程序以从DB获取的部分。
- MVC5:UserManager.AddToRole():“将用户添加到角色时出错:找不到UserId”?
- 在ASP.Net MVC 5应用程序中使用多个ASP Identity 2.0
- ASP.NET身份提供程序SignInManager保持返回失败
- 基于令牌的webapi实现以保护端点
- 网站初始化时创建默认用户/管理员 – 身份
- 如何在ASP .NET MVC 5中为AspNetUser创建SecurityStamp
- 刷新ASP.Net核心标识中的用户cookie票证
- 我应该如何从MVC 6视图中访问我的ApplicationUser属性?
- ASP身份2 + Web API令牌身份validation – 持久声明未加载