4

I have a site with a page that contains some tabs and when selecting one, its content is retrieved from the server using an AJAX call. Every tab is loaded through a different controller. For example, I have a Customer page which contains Products and Clients tabs.

The site has different types of users with different permission levels.

What I want to do is to protect the controllers, and show the content of the tabs only if the logged in user has permission. So if a user without permission enters the url of the controller, it should redirect to the login page. The url is like this:

http://localhost/MyApp/Products/1

where 1 is the database ID of the product.

I can implement these 2 solutions but none of them is optimal:

  1. Use the ChildOnlyAction attribute. I would mark the actions of the Product controller with this attribute and render the tabs from the main view using RenderAction. But it would mean that all the tabs on the page would have to be rendered, which is not optimal because I only want to load the data when the user clicks on the tab.

  2. On every request to the Product controller, I would make a database query using the ID of the record to check if the user has permission to access it. But this means that for every request I would have to run an extra query.

I'm wondering if there is a better approach to this.

SzilardD
  • 1,611
  • 2
  • 22
  • 40

2 Answers2

4

Similar to what Romias has suggested. You can combine the Authorize meta-attribute with a custom IAuthorizationFilter filter.

When you implement the Authorize meta-attribute you specify a list of users or roles that should have permission to that action. This lacks the ability to use a database to specify which ID's a user should have access to.

It is this ID-to-User mapping where the IAuthorizationFilter comes in to play. In the filter you can check the current user against the database.

A sample IAuthorizationFilter and its usage can be found on the following page:

http://geekswithblogs.net/brians/archive/2010/07/08/implementing-a-custom-asp.net-mvc-authorization-filter.aspx

Nick Bork
  • 4,831
  • 1
  • 24
  • 25
3

Have you tried using Authorize filter to decorate the controllers you want to protect?

[Authorize(Roles = "UserType1")]

You could also extend the Authorize filter to add your own logic. Here you can see an example of extending Authorize filter: https://stackoverflow.com/a/428266/7720

Community
  • 1
  • 1
Romias
  • 13,783
  • 7
  • 56
  • 85
  • Without a custom IAuthorizationFilter, setting the roles or even users won't work. In order to filter based on the ID you would need both the Authorize attribute as well as the custom IAuthorizationFilter. – Nick Bork Dec 05 '11 at 17:26