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?
What is Role Based Authentication In ASP.NET MVC? Role Based Authentication is Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization.
Open Visual Studio 2015 or an editor of your choice and create a new project. Choose "web application" project and give an appropriate name to your project. Select "empty" template, check on the MVC box, and click OK. Right-click on the Models folder and add a database model.
Using AuthorizeFilter, we can control the access in our MVC/Web API application by specifying this attribute in controller or action method. Role based authorization checks whether login user role has access to the page or not. Here developer embeds the roles with their code.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With