How do I start a thread in a different security context?

I believe that you can just set the CurrentPrincipal as first operation of the thread code after the thread has started, and only then begin to execute the code which is supposed to run with the other principal.

This should take care of any .NET role-based checks. If you need impersonation as well for calls to the OS, you can impersonate the WindowsIdentity.

Code (may or may not work – didn’t test it):

public void Run(object principalObj) {
    if (principalObj == null) {
        throw new ArgumentNullException("principalObj");
    }
    IPrincipal principal = (IPrincipal)principalObj;
    Thread.CurrentPrincipal = principal;
    WindowsIdentity identity = principal.Identity as WindowsIdentity;
    WindowsImpersonationContext impersonationContext = null;
    if (identity != null) {
        impersonationContext = identity.Impersonate();
    }
    try {
        // your code here
    } finally {
        if (impersonationContext != null) {
            impersonationContext.Undo();
        }
    }
}

...

Thread thread = new Thread(Run);
thread.Start(yourPrincipal);

Leave a Comment