Reputation: 14736
I have a bunch of controllers and related views that need to have role based authentication applied on them. I am thinking of having a base controller with the [authorize] property definition on it so that I can have all controllers that inherit from that base class be available only after login. I have tested this to be working. I am not sure if this is the best practice or if there will be any pit falls going ahead in this approach.
In the future I will need to have certain pages be accessible to only users within a particular role. The list of roles will be from a database table. so instead of changing all the related controllers I just make that change in the base controller that it inherits from. Is this the right way to go about doing it?
Thanks for your time.
Upvotes: 2
Views: 5567
Reputation: 101150
You can combine any number of Authorize
attributes.
i.e. You can have a Authorize
attribute on your base controller and a more specific one on another controller (for instance specifying a role) and a most specific one on a controller action (specifying a role or a user)
[Authorize]
public class BaseController : Controller
{}
[Authorize(Roles="Administrator")]
public class AdminController : BaseController
{
[Authorize(Roles="SuperUser")]
public ActionResult SuperSecret()
{}
}
It will check all attributes and only revoke access if any of the attributes fail.
In the future I will need to have certain pages be accessible to only users within a particular role.
That's how role based authentication works.
The list of roles will be from a database table.
Load the roles into a custom IPrincipal
in the method OnPostAuthenticate
in global.asax.
so instead of changing all the related controllers I just make that change in the base controller that it inherits from.
I don't follow you on this requirement. Do you want to avoid specifying roles on your controllers?
Upvotes: 7
Reputation: 8667
It's all right to use a base controller class for your controllers.
However, I don't think you should tie your controllers' inheritance to your roles hierarchy. It doesn't seem clean to me.
I'd implement an inheritance tree of attributes, like:
class NormalUserRolesAttribute: AuthorizeAttribute
class AdvancedUserRolesAttribute: AuthorizeAttribute
class AdminUserRolesAttribute: AuthorizeAttribute
with slightly different OnAuthorization
behavior and then mark your controllers with those attributes.
Upvotes: 1