目前,我正在用MVC数据库开发一个ASP.Net MVC 5应用程序。我需要实现基于ASP.Net标识2.0的身份验证和授权。我刚刚介绍了身份的基本概念,并试图在我的应用程序中实现相同的概念。由于数据库已经定义好了,所以我需要对身份进行一些定制。当我查看数据库时,表与我通常在示例标识项目中发现的表略有不同。

从图像中可以看到,有一个名为、用户组、的表,并根据模块为它们定义了一组权限。默认情况下,用户可以访问相同的权限。如果要更改任何权限,可以通过在“用户权限”表中设置权限来覆盖该权限。
所以我的第一个问题是,ASP。使用自定义授权和授权的Net标识是实现这种场景的正确方法吗?
从视图的角度来看,我必须生成一个基于用户/用户组权限的菜单,并希望基于它们启用/禁用按钮。我能够根据数据库值生成菜单。但是我需要授权每个客户请求,为此,我认为AuthorizeAttribute是最好的选择。请建议一下?任何良好的设计模式或职位将受到赞赏。
发布于 2015-07-31 21:10:55
当然,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获取的部分。
https://stackoverflow.com/questions/29988858
复制相似问题