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?
+11
A:
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
2009-08-31 07:04:07
A:
VERY STRANGE stuff. For example: I added a new user "Smith" and what next?
Now i must open solution, Press Ctrl + H, change "[Authorize(Users = "Charles, Linus")]" to "[Authorize(Users = "Charles, Linus, Smith")]" and recompile project. Am I right ?
Brian J. Hakim
2010-07-13 14:38:23
I would say the best practice is to never create an [Authorize] for a specific user. Always do it to a role for reasons that are hopefully made more obvious by an example:Say the [Authorize] attribute was protecting an action that only an Administrator should access. You would make an "Administrator" role, and assign Charles, Linus, and Smith to it. Then, when a fourth administrator comes in ("Joe"), you don't have to change every [Authorize], you just have to give Joe the "Administrator" role. Much less maintenance as you add more users that way.
EdgarVerona
2010-07-14 16:53:19