问题描述
我写一个ASP.NET MVC 3应用程序,我有很多角色:
I am writing an ASP.NET MVC 3 application and I have a number of roles:
系统管理,客户管理,预算所有者,应用所有者
System Admin, Customer Admin, Budget Owner, App Owner
我知道我可以很容易地使用限制访问某些控制器(和行动方法)[授权(角色=...)]属性。
I know that I can easily restrict access to certain controllers (and action methods) using the [Authorize(Roles="...")] attribute.
然而,有些授权是不是纯粹的基于角色的,但对权限。例如,业主预算只能够访问分配给他们的成本中心的预算 - 而不是其他人的预算
However some of the authorisation is not based purely on role, but on permissions. For example the budget owners should only be able to access budgets assigned to their cost centre - not other peoples budgets.
在present我有action方法中的一些code来检查这一点:
At present I have some code within the action methods to check for this:
if(UserCapabilities.CanAccessBudget(budgetId))
{
// get budget and show view
}
else
{
// redirect to index action
}
这是开始让我的code凌乱,并检查安全的噩梦 - 因为我有需要这些不同类型的授权检查的许多动作方法
This is starting to make my code messy and make checking security a nightmare - as I have many action methods that need these different types of authorisation checks.
这是我有一个想法就是编写一些自定义属性,我可以用它来装饰我的行动方法和清理我的code:
An idea that I have had is to write some custom attributes that I can use to decorate my action methods and clean up my code:
//
// GET: /Budgets/View/1
[CanAccessBudget]
public ActionResult View(int id)
{
//...
}
什么人认为?正在写自定义属性去最清洁和维护的方式?
What do people think? Is writing custom attributes the cleanest and most maintainable way to go?
推荐答案
您可以编写一个自定义授权属性:
You could write a custom authorization attribute:
public class CanAccessBudgetAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var request = httpContext.Request;
var budgetId = request.RequestContext.RouteData.Values["budgetId"]
?? request["budgetId"];
var currentUser = httpContext.User.Identity.Name;
return HasPermissionsForBudget(currentUser, budgetId);
}
return isAuthorized;
}
}
和则:
[CanAccessBudget]
public ActionResult View(int id)
{
//...
}
这篇关于ASP.NET MVC 3自定义授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!