0

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:

  1. A set of users
  2. A set of roles (for example, enum Role)
  3. Every user have his own set of his roles.
  4. Every class/method could be specified for particular role.

    [AuthorizationAttribute(Roles = new Role[] { Role.Admin })] public class UserService : IUserService {

    }

  5. 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.

Sir Hally
  • 2,318
  • 3
  • 31
  • 48
  • I've really couldn't find any reason to close this question - there is a great answer from Akton. So, It IS NOT difficult to tell what is being asked here. – Sir Hally Sep 09 '12 at 11:15

1 Answers1

3

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:

  1. Implement the IContextAttribute.GetPropertiesForNewContext(IConstructionCallMessage) method. You create an object, call it MySecurityProperty, that implements the IContextProperty and IContributeObjectSink interfaces and add it to the IConstructionCallMessage.ContextProperties collection.
  2. In the implementation of MySecurityProperty.GetObjectSink(MarshalByRefObject, IMessageSink) construct an object, call it MySecurityAspect, that implements the IMessageSink interface.
  3. In the implementation of MySecurityAspect.SyncProcessMessage(IMessage), you actually check the call to see whether it is valid. If it casts to IMethodMessage, indicating a method call, you can query the properties of IMethodMessage to 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.

akton
  • 14,148
  • 3
  • 43
  • 47
  • Yes, it is really good solution for my problem and it is works for me. Thank you, you've helped me a lot. – Sir Hally Sep 09 '12 at 11:12