Common problem: How to implement user access rights differentiation system in any .NET application (for example, WCF application) by using class/method attributes?
So, we have:
- A set of users
- A set of roles (for example, enum
Role) - Every user have his own set of his roles.
-
Every class/method could be specified for particular role.
[AuthorizationAttribute(Roles = new Role[] { Role.Admin })]
public class UserService : IUserService
{}
-
If user’s set of roles doesn’t contain this role, user mustn’t have access to the method.
Update. I’ve tried to make the problem description more clear. The Akton’s solution is good for this problem.
It is possible to create an attributed security model like you suggest but it is not easy. Your securable objects have to inherit from ContextBoundObject and your security attribute from ContextAttribute (or implement the IContextAttribute interface). Then:
MySecurityProperty, that implements theIContextPropertyandIContributeObjectSinkinterfaces and add it to theIConstructionCallMessage.ContextPropertiescollection.MySecurityAspect, that implements the IMessageSink interface.IMethodMessageto see whether it is calling a method or class with your security attribute and do the appropriate checks. If the call is unauthorized, throw an exception of the appropriate type.It will take you a few hours to get it working but, once it does, it makes sense. It is just a very undersupported part of the .Net framework. The big problem, beyond the complexity, is that it forces your securable classes to inherit from ContextBoundObject rather than any other library classes. ContextBoundObject also inherits from MarshalByRef, which can interfere with serialization.
See http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/3/ for a more in depth explanation.