ASP.NET MVC 3 User Authorization

I am writing an ASP.NET MVC 3 application and I have several roles:

System administrator, client administrator, budget owner, application owner

I know that I can easily restrict access to certain controllers (and action methods) using the [Authorize (Roles = "...")] attribute.

However, some authorizations are not based solely on role, but on permissions. For example, owners of budget funds should have access only to the budgets assigned to their cost centers, and not to the budgets of other nations.

I currently have code in action methods to test this:

if(UserCapabilities.CanAccessBudget(budgetId)) { // get budget and show view } else { // redirect to index action } 

This starts to make my code dirty and makes the security check a nightmare - since I have many action methods that need these different types of authorization checks.

The idea I got is to write some custom attributes that I can use to decorate my action methods and clear my code:

 // // GET: /Budgets/View/1 [CanAccessBudget] public ActionResult View(int id) { //... } 

What do people think? Is writing custom attributes the cleanest and most convenient way for you?

+7
source share
2 answers

You can write your own 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; } } 

and then:

 [CanAccessBudget] public ActionResult View(int id) { //... } 
+15
source

It is better to put the authorization / redirection logic in ActionFilterAttribute because you are looking for permissions (which are based on the parameters of the action, and not just what roles the user takes).

Although the logic of refactoring an attribute that is used only once can become messy (with tons of attributes).

0
source

All Articles