How should add-ins in restricted AppDomains access escalated services
I've currently used MAF to create an add-in model where the add-ins are loaded in a restricted AppDomain (Internet permissio开发者_如何学运维n). This means that the add-in can't call our database which is what we want in most cases as we want to prevent add-in authors running any queries directly against the db.
We want them to use some form of host API that will allow them to perform certain tasks (e.g. run very specific queries or send emails). Can anyone tell me the best way to do this?
I've tried to setup the AppDomain to treat the assembly that contains the host API as a full trust assembly while running the add-ins in a restricted way, however I still get SecurityExceptions when I attempt to open a db connection.
OK, I've managed to solve this. For people who need to know:
Create an assembly with the Host API in it and allow the add-in to reference it.
Ensure the assembly that contains the Host API has the [AllowPartiallyTrustedCallers] attribute on at the assembly level and strong name the assembly.
Ensure the Host API assembly is registered with the AppDomain as a full trust assembly (see Link on how to do this).
Ensure the methods on the Host API that require escalated permissions are decorated with the [SecuritySafeCritical] attribute (.NET 4).
Demand full trust at the start of each method you need escalated permissions and then remove the demand straight after. The code below provides a method that takes a delegate which will be run in full trust.
/// <summary> /// Runs the supplied delegate using full trust /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> private static T RunWithFullTrust<T>(Func<T> func) { //NOTE: This line grants the method full trust new PermissionSet(PermissionState.Unrestricted).Assert(); T result = func(); //Undo the grant for full-trust! CodeAccessPermission.RevertAssert(); return result; }
Also, prior to loading any add-ins ensure that the Host API is loaded into the restricted AppDomain. This'll avoid exceptions where the Host API assembly cannot be found.
精彩评论