0

I am learning ASP.NET MVC3, and I just created a controller for my Model/Context. However, anyone can navigate to these pages and use them. How can I set permissions for these pages?

LunchMarble
  • 5,079
  • 9
  • 64
  • 94
  • 2
    I recommend visiting http://www.asp.net/mvc/overview/security before asking such general questions. – marapet May 10 '12 at 18:12

2 Answers2

2

AuthorizeAttribute will be your first line of defense. You can grant access based on group membership or username. Works a lot like Code Access Security / Principal Permission Attributes but isn't as hard to work with.

Example:

// Allow Everybody in
public ActionResult Index ()
{}

// Allow only Editors/Admin to post edits back to controller.
[HttpPost]
[Authorize(Roles="Admin,Editor"]
public ActionResult Edit(EditViewModel vm)
{}

You can use them at the Class or Method Level, so you can have a base controller that only lets authorized users use certain controllers of your app.

If you find yourself using the same groups or users over and over, I would create an override of the AuthorizeAttribute that has those groups predefined, that way you don't misspell or forget them. This will also DRY up your code, which is always great.

Alex Moore
  • 3,415
  • 1
  • 23
  • 39
1

You can use the Authorize attribute to rstrict permission, often this is inherited from the base class. This is the most common and recommended.

You can use the ActionFilter attribute and override the OnActionExecuting and set custom logic in there. Possible, but not the recommended.

There are lots of other ways too, but the prior two are the main ones for MVC.

Thinking Sites
  • 3,494
  • 17
  • 30