【发布时间】:2017-04-09 08:54:45
【问题描述】:
我有一个 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);
优点:
- 每个方法都可以隐式访问角色。
缺点
- 难以进行单元测试,因为它依赖于静态对象
2) 将角色作为参数传递给需要它的方法,例如
public IUserService {
void CreateUser(User user, string role);
}
优点
- 易于单元测试,因为角色已显式传递给方法
缺点
- 每个方法都需要有一个参数
- 如果授权从基于角色的授权更改为任何形式的授权,都会破坏系统
有什么选择?在业务层实现基于角色的授权的标准方式是什么?
【问题讨论】:
标签: c# asp.net-mvc authorization claims-based-identity