I am searching for a good approach to automatically check the access rights when accessing a propertys getter and setter.
This is just for curiosity and experimental purposes, so performance does not really matter.
One Approach I found is the following (example is just for getters):
public class DynamicPropertyClass : DynamicObject
{
/// <summary>
/// I want this to work for a default auto-property
/// </summary>
public string TestString { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (StaticSecurityContext.CheckSecurityCondition(binder.GetType(), binder.Name))
{
return base.TryGetMember(binder, out result);
}
else
{
throw new SecurityException();
}
}
}
Using a dynamic object to abort if the Security Conditions are not given. The problem with this approach is that properties that actually exist on the class won't get handled by the TryGetMember method. So this approach forces me to only handle properties that do not actually exist in code.
As you can see the dynamic capabilitys are not really relevant for my approach. I want something similar to work on my properties written in code, dynamic capabilitys do not have to be supported.
So, is there another approach, possible in c#, without applying attributes on every property or adding custom code to the getters and setters?
It is an old question, but I thought it'd be interesting to contribute since DynamicProxy was not mentioned. You can also use the DynamicProxy nuget package from Castle.Core.
You can intercept calls to Get and Set methods for all the virtual properties of your class.
I have written a Gist explaining the concept, tracking when properties are being accessed and set.
Here is what the Interceptor looks like.
The creation of the proxy is done like so:
The TrackedClass must have virtual properties:
The test is here (using xUnit):
You can use a proxy pattern. It exist a lot of implemention provided by AOP framework but if performance is not condition, you can simply try Transparent/RealProxy used by remoting API.
https://msdn.microsoft.com/fr-fr/library/system.runtime.remoting.proxies.realproxy(v=vs.110).aspx