If you want to ensure that only callers that have a specified permission can call your code, you can programmatically or declaratively demand that callers of your code have specific a permission or permission set. Demands cause the runtime to perform security checks to enforce restrictions on calling code. During a security check, the runtime examines the permissions of each caller in the call stack, checking to see whether the permission that is being demanded has been granted to each caller. If a caller is found that does not have the demanded permission, the security check fails and a SecurityException is thrown. You can cause a security check to take place every time a particular method is called or before a particular block of code is executed. Or, if you want the security check to occur when any member of a particular class is called, you can place the demand so that it applies to every member of the class. The remainder of this topic explains how you make security demands, when you should do so, and why you might choose one type of security demand over another.
If you are writing code that directly accesses a protected resource and if this access is exposed to the caller, you must make a security demand to ensure that all callers in the call stack have permission to access that resource. Your demands can be declarative demands or imperative demands. However, no matter what type of demand you make, there are some general guidelines to follow.
If you want to ensure that the caller originated from a particular site or zone, you can demand that callers have a particular identity permission. However, it is recommended that you do this only when you are giving additional access based on matching an identity, not when you are denying access based on matching identity. The reason for this is that it is relatively simple to modify or mask code's identity, so denying access based on identity alone is not a reliable way of protecting your code and the resources it accesses from unauthorized access.
When you want to ensure that an object cannot be created except by callers who have a specific permission, you should place the demand on the constructor for that object. For example, suppose you have a class called myFileStream, which derives from the frameworks FileStream class, and you want to ensure that only authorized callers can create instances of myFileStream. You would place a declarative or imperative demand on the constructor(s) of the myFileStream class.
You can also put demands in code that sets or gets a property. In general, you put demands for less restrictive permissions on the get accessor (the Property Get in Visual Basic) than on the set accessor (the Property Let or Set in Visual Basic).
Note: Role-based security checks have slightly different semantics than code access security checks do. For more information, see the Role-based Security topic.