AuthorizeAttribute
attribute, but it clearly lacks the capabilities and flexibility (or rather, there are practically none). Rights can be defined only at the development stage and cannot be changed without recompiling. But to create your own attribute with the necessary functionality is not at all difficult.PermissionManager
class: public class PermissionManager { public bool ValidatePermissions(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; } }
IAuthorizationFilter
interface, in which the only OnAuthorization
method is OnAuthorization
. This method is called if necessary to authorize the user, i.e. check if he has rights to this operation. This is exactly what we need. Well, enough of the theory, let's start creating the attribute itself, i.e. class DynamicAuthorizeAttribute
: public class DynamicAuthorizeAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(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)) { throw new UnauthorizedAccessException(" "); } } }
AuthorizationContext
there are many useful properties that make it possible to organize the checking of access rights in many ways, but in this case the check is elementary, we just use the method of the PermissionManager
class.Home
controller: public ActionResult Test() { return View(); } public ActionResult Edit() { return View(); }
[Attributes.DynamicAuthorize] public class HomeController : Controller
Index
view: <p> @Html.ActionLink("Test", "Test") </p> <p> @Html.ActionLink("Edit", "Edit") </p>
Source: https://habr.com/ru/post/137581/
All Articles