I have a mvc application, where I have different roles of uses, and a role user have different functionality (ex: add, edit, delete,--), and a user in each role will have sub set of this functionality in this role. I want to give permission to each user to view the pages based on this permissions.
What would be the best way to achieve this in mvc?
Thanks
In our application we have roles and each role has many functionalities. Our goal was to control access at the functionality level instead of role level using less access to the database as possible.
Here is what we do:
1) At the login, we create an UserCredentials object which contains all functionalities that the user has access (based on its roles). It is a "distinct" of all functionalities contained in all roles the user has access. Then we store this UserCredentials in session.
2) To restrict access to controllers or actions, we have implemented an attribute that inherits AuthorizeAttribute and we use like:
[Secure(Functionalities="Xyz.View,Xyz.Save")]
public ActionResult SomeAction(...){ ... }
Note that there is no database call, all we do is to check that "Xyz.View" is in the functionalities list stored in the UserCredentials.
3) Sometimes we need to access the credentials from inside the action, so we have created another ActionFilter (global) which will inject the credentials in the action parameters for you if he finds a parameter named "credentials", for instance:
public ActionResult SomeAction(UserCredentials credentials, int otherParameters)
{
// "credentials" is populated by the global action filter
}
You could use this to show a different view based on the user Roles or Functionalities.
4) Another scenario is when we need to hide portions of our views based on user roles or functionalities. For this, we have created a BaseViewModel which has a UserCredentials property. This property is also populated by another global ActionFilter that runs AFTER the action is executed. If the model inherits BaseViewModel, then the filter populates UserCredentials property. We can do something like:
@if(Model.UserCredentials.IsInRole("X")){
<div>Some content</div>
}
or
@if(Model.UserCredentials.HasAccessTo("Xyz.Save")){
<button>Save</button>
}
I hope it helps.
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