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

15 浏览
0 Comments

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

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

从图片中可以看到,有一个名为“用户组”的表格,并根据模块定义了一组权限。用户默认情况下可以访问相同的权限。如果您想更改任何权限,可以在用户权限表中设置权限来覆盖它。

所以我的第一个问题是,ASP.Net身份验证和授权是否是实现这种场景的正确方法?

从视图角度来看,我需要根据用户/用户组的权限生成菜单,并根据这些权限启用/禁用按钮。我已经能够根据数据库值生成菜单。但我需要对每个客户端请求进行授权,我认为使用AuthorizeAttribute是最好的选择。请给予建议?任何好的设计模式或文章都将受到赞赏。

0
0 Comments

自定义身份验证和授权是基于用户权限的,这是因为使用Identity可以非常强大和灵活地进行自定义。可以将用户权限作为声明,然后编写自定义的AuthorizeAttribute来检查这些声明。例如,考虑以下代码:

[HttpPost]

public ActionResult Login(string username, string password)

{

if (_userManager.IsValid(username, password)) // your own user manager

{

var ident = new ClaimsIdentity(

new[]

{

// 添加以下两个声明以支持默认的防伪提供程序

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),

// 从数据库中获取分配的用户权限ID,并将每个权限ID作为声明添加到身份中

new Claim("UserRight","FirstAssignedUserRightID"),

new Claim("UserRight","SecondAssignedUserRightID"),

},

DefaultAuthenticationTypes.ApplicationCookie);

HttpContext.GetOwinContext().Authentication.SignIn(

new AuthenticationProperties { IsPersistent = false }, ident);

return RedirectToAction("MyAction"); // 授权成功

}

// 无效的用户名或密码

ModelState.AddModelError("", "invalid username or password");

return View();

}

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

public class ClaimsAccessAttribute : AuthorizeAttribute

{

// 在实际的情况中,可以从数据库中获取声明的值,这里简化了示例

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()

{

// 通过将User.Identity转换为ClaimsIdentity,您还可以访问已验证用户的声明

// ((ClaimsIdentity)User.Identity).Claims

}

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

0