thinkmmk
thinkmmk

Reputation: 487

Controlling the accessibility of Action methods of Controller(s) in mvc

I have a MVC 3.0 application which 3 controllers and action methods in it. The application is login based. And once the user is authenticated he is landed on the homepage where he sees the 3 menu links which are mapped to the action methods of the three controller. The user can click the links or enter the url in the address bar and can navigate to the respective page.

But now the links have become role based like,

If IsProductPageAllowed=true then only user can see the ProductPage.

If IsMediaPageAllowed=true then only user can see the MediaPage.

I have handle the visiblity of the links easily in the HomePage view depending on the property valuetrue/false.

But was looking for a correct way to block the user of accessing the ProductPage if he enters the url in address bar directly and if the value is false. I can do this easily on each action method of the controller by checking the true false property and accordingly redirect to homePage if the value is false.

I was thinking of some better way to do this, like in Controller itself.

Thank you,

M.

Upvotes: 0

Views: 184

Answers (2)

Dattatray
Dattatray

Reputation: 26

Define a Custom Security Filter that will intercept all the requests and authorize them before processing. If authorization is not successful the user will be redirected to an error page for Insufficient Permissions.

The permissions will be in terms of whether a specific role can call a specific Action of a Controller or not. There will also be a basic authorization that will redirect a user to a login page if he is not logged in.

Upvotes: 1

Komengem
Komengem

Reputation: 3764

If you are using SimpleMembership, why don't you assign Roles to each membership. That way you can do this to restrict access to any action or even an entire controller.

[Authorize(Roles="Admin")] 
public ActionResult Contact()
{
   ViewBag.Message = "Your contact page.";
   return View();
}

With code above, only the admin user will gain access to that action. if you want to restrict an entire controller, just place [Authorize(Roles="Admin")] on top of the controller name.

If you need help on how to seed Roles into your database, read Kevin's Blog here

Upvotes: 1

Related Questions