Dynamic Access Control for ASP.NET MVC
AuthorizeAttribute, but it obviously lacks the capabilities and flexibility (more precisely, there are practically none). Rights can only be determined at the development stage and cannot be changed without recompilation. But to create your own attribute with the necessary functionality is not at all difficult.So let's get started. Create a new project in Visual Studio, select the type ASP.NET MVC 3 Web Application, call DynamicAuthorize . We are waiting for the studio to generate the project.
How to store and determine access rights can be done in various ways: in the database , received from a remote service, in an xml file, etc. It all depends on the task and your preference. For example, in order not to be distracted by the implementation of these mechanisms, we will make a class that returns information about permissions, replace it with the implementation you need, I think it will not cause problems. Actually class
PermissionManager:publicclassPermissionManager
{
publicboolValidatePermissions(string controller, string action, string user)
{
bool isUserAccess = false;
if (user == "user1" && controller == "Home")
{
switch (action)
{
case"Test":
isUserAccess = true;
break;
}
}
if (user == "user2" && controller == "Home")
{
switch (action)
{
case"Edit":
isUserAccess = true;
break;
}
}
// Незарегистрированных ползователей пускаем на главную и "О проекте"if (controller == "Home" && (action == "Index" || action == "About"))
{
isUserAccess = true;
}
return isUserAccess;
}
}The class is elementary, so I think it's not worth explaining what it does. As for authorization itself, MVC has an interface
IAuthorizationFilterin which a single method is defined OnAuthorization. This method is called if necessary to authorize the user, i.e. check whether he has rights to this operation. This is just what we need. Well, enough theory, we proceed to create the attribute itself, i.e. class DynamicAuthorizeAttribute:publicclassDynamicAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
publicvoidOnAuthorization(AuthorizationContext filterContext)
{
PermissionManager permissionManager = new PermissionManager();
string action = filterContext.ActionDescriptor.ActionName;
string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string user = filterContext.HttpContext.User.Identity.Name;
if (!permissionManager.ValidatePermissions(controller, action, user))
{
thrownew UnauthorizedAccessException("Пользователю не разрешено использование данного действия");
}
}
}The type parameter passed
AuthorizationContexthas many useful properties that make it possible to organize access control in many ways, but in this case the check is elementary, we just use the class method PermissionManager. On this, in fact, the creation of dynamic authorization is completed. I said that it’s not difficult. Well, let's start the tests. Let's create two additional actions (two of us were kindly created by the studio) of the controller
Home:public ActionResult Test()
{
return View();
}
public ActionResult Edit()
{
return View();
}We create representations for them (I used the Visual Studio generator)
And mark the controller with our just created attribute:
[Attributes.DynamicAuthorize]
publicclassHomeController : ControllerAdd
Indexlinks to the created controller actions to the view :<p>
@Html.ActionLink("Test", "Test")
</p><p>
@Html.ActionLink("Edit", "Edit")
</p>Now you need to assemble the project, press Ctrl + Shift + B , it should work without errors.
Now we will create test users, run ASP.NET Admin tools

Go to the "Security" section and add 2 users with the names user1 and user2 . Everything can start the project. Now, if you click on one of the links without authorization, you will receive an access error. If you log in as user1, the Test action will be available, but Edit is not available. If you log in as user2, then the opposite is true.
In conclusion, I would like to say that despite the simplicity of implementation, newcomers often have a question how to organize a dynamic check of access rights. I hope this post will help people who are faced with this issue to deal with it and make authorization exactly the way it was intended.
You can download the project here .