I recently read an interesting blog about implementing Role-based access in MVC using custom attributes. I have implemented a similar strategy for Permission-based access by using the session object.
Storing the permissions
I usually define a user’s permissions as an enumeration and then simply store this as an integer in the database. You might need permissions to be defined at a group or role-level, but in most cases this will do what is required. YAGNI!
This is the set of permissions I’m going to use for specifying access rights on my actions.
Store the user object in the session
We’re going to need access to the current user’s permissions if we want to determine if the current user has the necessary permissions to perform a certain action. I find the easiest thing to do is to simply store the current user in the session. I’ve had some lively debates around this – the best argument against this being that any changes to the user object will cause all users to lose their sessions. While this is a valid argument, I prefer doing the simplest thing that could possibly work. YAGNI!
Create a custom attribute for authorizing access
The last step is to create a custom attribute for authorizing access to our actions.
And that’s all we need. Now we can specify the necessary permissions on each controller action.