views:

47

answers:

1

What are some different solutions to wrapping access to functionality within a .NET MVC application?

For example, I have six tabs that represent different areas of the application and within area 1, there is the ability to add, edit, upload, whatever.

I need a central way to say:

  1. Build some dictionary of what the user can do
  2. Wrap tabs, buttons, links, etc, validate the user can access this piece of functionality and show/hide appropriately.

I know I can restrict access to actions via action filters and roles, but what about from the UI?

Any help would be appreciated. I am sure I am not the only one who has needed to do this, thanks!

+1  A: 

First of all, you'll want to perform server-side authorization as well. Anyone can impersonate your client and call your controllers directly, circumventing your client-side authorization.

But here's what I'd do:

Create an AuthorizationService to store this business logic centrally. It'll have methods like:

public bool CanEditSomeObject(Guid userId, Guid objectId)

Use this AuthorizationService inside your controller (or another service referenced by the controller) to construct the ViewModel with all the authorization information that view will need.

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Edit(Guid id)
    {
        bool currentUser = _userService.GetUser(User.Identity.Name);
        bool canEditSomeObject = _authenticationService.CanEditSomeObject(currentUser.Id, id);
        var viewModel = new SomeObjectViewModel {CanEditSomeObject = canEditSomeObject};
        return View(viewModel);
    }

Make your view strongly typed and modify the HTML based on the model. You could use things like partial views to make this cleaner. But you'll just hide, disable, or not include HTML for things the current user doesn't have access to.

<%= if (Model.UserCanEdit) Html.RenderPartial("EditForm.ascx") %>

In addition, if you need to change things dynamically on the client-side (e.g., user does action a, so now they can perform action b) you can use JQuery to manipulate the HTML. You can even use JQuery to call into your controller to ask it questions if you want (see this question), but I'm not sure that's necessary.

manu08
Do you have some sample code?
Robert Harvey
Nice! Thanks for the suggestions, I will try that out.
Kevin