How can I prevent a third party from calling certain methods?

I have an assembly which is being developed to create a facade around some potentially sensitive functionality and I want to allow a third party to call some of the methods contained within it but not others.

How can I prevent the third party calling unauthorised methods given they will have access to the entire DLL (I'm not concerned about them seeing the code, just executing it)?

This has to be compatible with the .net compact framework so unfortunately using the StrongNameIdentityPermission attribute is not possible.


I think you should ship two Facade implementations, one for 'internal' consumers which exposes all methods and another external that exposes only the sub-set. You can achieve this whilst maintaining only one code base by having two separate build processes. One technique that springs to mind is to use compiler directives to exclude a method from the external build, or mark it internal if it is required by other public methods. If you do ship sensitive methods with internal modifiers you may also want to implement obfuscation.

EDIT

Perhaps it would be cleaner, rather than having directives around each method to use partial classes, define a partial class for the sensitive methods and put the entire class implementation in a directive.

    public partial class MyClass
    {
        public void NonSensitive(){}
    }

    #if INTERNAL_BUILD
    public partial class MyClass
    {
        public void Sensitive(){}
    }
    #endif

You can have this partial class in the same or a separate file, which might be a nice level of separation as you could prepend the file name x_Sensitive.cs or similar.


Description

Assuming i understand your question.

You can mark your methods with the internal access modifier to make them not accessable from other librarys.

But this does not help from security persepective, because it is always possible to run the method using reflection.

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

More Information

  • MSDN - internal (C# Reference)

  • If a third party can see the code, then they can run it - there is nothing you do to stop this.

    Note however you have an application which is loading 3rd party plugins then you could load plugin assemblies with restrictions that prevent it from using reflection - this would mean that you can mark these methods / classes as internal to prevent plugins from being able to call these methods when loaded as a plugin in your application . Depending on the nature of the sensitive functionality this may or may not be useful to you from a security perspective.

    For information on how to do this see How to: Run Partially Trusted Code in a Sandbox

    链接地址: http://www.djcxy.com/p/57550.html

    上一篇: 在elasticsearch中计算地理距离

    下一篇: 我怎样才能防止第三方调用某些方法?