业务层中基于角色的授权

时间:2017-04-09 08:54:45

标签: c# asp.net-mvc authorization claims-based-identity

我有一个3层应用程序 - 1)UI层是一个ASP .NET MVC应用程序2)Business层是一个类库3)数据访问层是一个类库。我使用基于声明的基于角色的授权。我在Application_AuthenticateRequest事件处理程序

中设置了声明
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
            var authenticationCookie = 
    HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            var ticket = FormsAuthentication.Decrypt(authenticationCookie.Value);
            FormsIdentity formsIdentity = new FormsIdentity(ticket);
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity);
           // Get the roles from database
              ... 
             var role = GetUserRole();      
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role));

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            Thread.CurrentPrincipal = claimsPrincipal;  
}

现在我有两种方法可以访问业务层中的角色

1)直接从线程主体

访问角色
var principal = Thread.CurrentPrincipal as ClaimsPrincipal;
   var claim = principal.Claims.FirstOrDefault(x => x.Type == 
   ClaimTypes.Role);

优点:

  • 每个方法都可以隐式访问该角色。

缺点

  • 难以进行单元测试,因为它依赖于静态对象

2)将角色作为参数传递给需要它的方法,例如

 public IUserService {

    void CreateUser(User user, string role);
   }

赞成

  • 易于单元测试,因为角色已明确传递给方法

缺点

  • 每个方法都需要一个参数
  • 如果授权从基于角色的授权更改为任何形式的授权,则会破坏系统

有什么替代方案?在业务层实施基于角色的授权的标准方法是什么?

1 个答案:

答案 0 :(得分:0)

有一种标准方法可以跨多个层实施外化,细粒度授权(不仅仅是基于角色)。该模型称为,代表基于属性的访问控制。有一个实现它的主要框架,它被称为。另一种替代方案是.Net中基于声明的授权。

ABAC / XACML定义:

  1. 用于定义授权规则的策略语言,例如a manager can view documents they own
  2. 一方面定义的架构

    一个。策略决策点(PDP),处理授权请求并产生决策(允许/拒绝)

    湾策略执行点(PEP),用于保护您的应用程序,拦截业务请求并向PDP发送授权请求。这是代码中的一段代码,可以作为过滤器,拦截器,注释或更多...

  3. 使用外部授权的好方法是,您可以一次性跨多个层应用相同的一致授权(从Web SSO到业务层甚至数据层)。

    HTH。维基百科上有很多资源。您还可以查看此blog我尝试保持最新。

    The XACML Architecture