Being relatively new to ASP MVC, I'm unsure which would better suit my needs. I have built an intranet site using Windows authentication and I'm able to secure controllers and actions using the Active Directory roles, e.g.
[Authorize(Roles="Administrators")]
[Authorize(Users="DOMAIN\User")]
public ActionResult SecureArea()
{
ViewBag.Message = "This is a secure area.";
return View();
}
I need to define my own security roles independent of the AD roles. The desired functionality is that authenticated users are granted access to specific actions according to one or more roles associated with their profile in my application database e.g: "Manager", "User", "Guest", "Analyst", "Developer" etc.
How do I create a custom role provider and/or custom authorization attribute(s)?
My solution was to create a custom role provider. Here are the steps I took, in case anyone else needs help later:
Create your custom user and role classes
and
Set up your database context
Create your role provider and implement the following methods
Edit your web.config to set up the database connection and role provider reference
and
In package manager console, enable migrations
In the newly created Configurations.cs set up the user/role stores and managers and configure the user manager validator to accept '\' characters
In package manager console, ensure the database is created and seeded
Create a custom authorization attribute that will redirect to an access denied page on failure
You're done! You can now create an access denied page (in this case ~/Home/AccessDenied) and apply the attribute to any action, e.g.
Hope this helps someone in the future. Good luck!