Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
1.1k views
in .Net Framework by 39 42 54
edited by
I am working on an MVC solutions and I want to prevent unauthorized users from accessing specific controllers or actions based on their permissions, How can I do that in MVC?

1 Answer

2 like 0 dislike
by 39 42 54
edited by
 
Best answer

Prevent unauthorized users from accessing specific controllers or actions based on their permissions MVC

To prevent unauthorized users from accessing specific controllers or actions based on their permissions MVC, you should follow the below steps:

  1. Create a Custom Filter
  2. Inherit from ActionFilterAttribute
  3. Override OnActionExecuting:
  4. Get Current Controller and Action
  5. Check User Permission
  6. Apply the Attribute

*Steps in details

  1. Start by creating a custom filter named "PreventDirectAccessAttribute."
  2. Inherit the "PreventDirectAccessAttribute" from "ActionFilterAttribute" to make it an action filter.
  3. Within your custom filter, override the "OnActionExecuting" method. This method will be called before an action method in your controller is executed.

     public class PreventDirectAccessAttribute : ActionFilterAttribute
     {
             public override void OnActionExecuting(ActionExecutingContext filterContext)
             {
                    base.OnActionExecuting(filterContext);
              }
     }
    
  4. Retrieve the current controller and action from the incoming HTTP request using the following code:

       var controllerName = filterContext.RequestContext.RouteData.Values["controller"] as string;
       var action = filterContext.RequestContext.RouteData.Values["action"] as string;
    
  5. Determine the user's permissions and apply your access control logic. For example:

        if (userPermission > 0 
            && userPermission==(int)Permission.CreateRequest
            && !((controllerName.Equals(Resources.Labels.ControllerApplication))
            && action.Equals(Resources.Labels.ActionCreateApplication)))
        {
            // Access is allowed
        }
        else
        {
            // Access is denied
        }
    
  6. Add the "PreventDirectAccessAttribute" above the controller name or action methods where you want to enforce this access control. For example:

      [PreventDirectAccessAttribute]
      public class BaseController : Controller
      {
       
      }
    
If you don’t ask, the answer is always NO!
...