1

I have a ASP.NET MVC 4 application. I am trying to implement a solution where I check if a user can access a view, if not then display an error. If the user can access a view then I need to check if that user has read access or read and edit access to that view. If the user has read access then just a normal details view is displayed, if read and edit access then the user can see a details view or can edit the data.

Is something like this possible? I have tried looking through a couple of starter kits that I found on Codeplex but I can't find something like I want. How would this be implemented? If possible, if anyone knows of any sample project that I can download then I will appreciate. I like to work through code, I learn more this way.

I want this all to be database-driven.

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234

2 Answers2

1

You should look more into the AuthorizeAttribute and how to use roles. Basically you give your users roles (that may be fetched from the database) and for every view you wish to limit access in your application you add the Authorize attribute together with the roles. By default I think you can only limit to access or no access but you can probably override and write your custom attribute to give you the behavior you are interested in.

Alternatively, you can manage the user privileges in your controllers. Since you know the authenticated users roles and have access to them you can perform the check in the controller and create the view from that (disabled inputs etc.)

Related

Community
  • 1
  • 1
Marcus
  • 8,230
  • 11
  • 61
  • 88
0

As @Marcus said, you should use Attribute. When action starts, you can check user's role, he has access or not:

public class AttributeForTestAttribute : ActionFilterAttribute
{
    public int RoleCanAccess { get; set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
          base.OnActionExecuting(filterContext);

          //your validation here..
          //for example:

          if(_currentUser.Role < RoleHasAccess )
          {
            //user has not access to this action, redirect him to home page. 

            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "returnUri", filterContext.HttpContext.Request.RawUrl } });
          }
          else
          {
            // user has access to this action
          }
    }
}

And in controller use your Attribute:

    [AttributeForTest(RoleHasAccess = 2)]
    public ActionResult SaveProduct(Product product)
    {

    }
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90