我有一个3层应用程序 - 1)UI层是一个ASP .NET MVC应用程序2)业务层是一个类库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)直接从Thread主要通道的作用
var principal = Thread.CurrentPrincipal as ClaimsPrincipal;
var claim = principal.Claims.FirstOrDefault(x => x.Type ==
ClaimTypes.Role);
优点:
- 每种方法c隐式地访问该角色。
缺点
- 难单元测试,因为它是依赖静态对象
2)上作为参数传递给该方法需要它例如作用
public IUserService {
void CreateUser(User user, string role);
}
优点
- 容易进行单元测试,因为角色被明确传递给方法
缺点
- 每一个方法都需要有一个参数
- 如果授权基于角色的授权变更为任何形式的授权,它打破了系统
什么是另类?在业务层中实现基于角色的授权的标准方式是什么?