20

I'm interested in knowing what are the best practices for using role based security in MVC:
how to secure your actions and make them accessible by specific roles only?

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
MichaelT
  • 7,574
  • 8
  • 34
  • 47

1 Answers1

24

If you setup your ASP.Net membership provider correctly, you can easily use the [Authorize]-attribute to specify access for different roles or users.

To require users to login, use:

[Authorize]
public class SomeController : Controller

// Or
[Authorize]
public ActionResult SomeAction()

To restrict access for specific roles, use:

[Authorize(Roles = "Admin, User")]
public class SomeController : Controller

// Or
[Authorize(Roles = "Admin, User")]
public ActionResult SomeAction()

And to restrict access for specific users, use:

[Authorize(Users = "Charles, Linus")]
public class SomeController : Controller

// Or
[Authorize(Users = "Charles, Linus")]
public ActionResult SomeAction()
Mickel
  • 6,658
  • 5
  • 42
  • 59
  • 1
    What if you wish your roles/permissions to be dynamic in the DB? – Joe Phillips Jul 09 '13 at 01:28
  • @JoePhilllips Create a custom attribute, and onAuthorize handler. – nagytech Jul 09 '13 at 01:33
  • I like the Authorize method decoration. Here's a follow up question: if we have an active directory group created to deal with exceptions to the rule.. e.g. a group named "MyApp_AccessDenied" .. is there a way to use that.. i.e. a negative version of the Authorize decoration... like a DenyAuthorize decoration? – Bkwdesign Sep 18 '13 at 14:49