How to start a thread in the security context of a different user? When a process starts a thread normally the security context is also passed but how to launch a thread in a different security context with the principal of a different user?
-
Related [post](https://stackoverflow.com/a/7250145/465053) - How to impersonate an AD account to run a piece of code while running an application? – RBT Jul 06 '17 at 10:19
2 Answers
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);

- 59,176
- 9
- 122
- 152
-
1A code snippet to along would be nice. I think the ExecutionContext flow should be suppressed also. – TrustyCoder Apr 09 '10 at 14:30
-
1Why should the `ExecutionContext` flow be suppressed? When using impersonation (as I did it here), the `SecurityContext` of the `ExecutionContext` is updated (checked with Reflector, this happens in the internal `UpdateThreadWI` method in the MS implementation). – Lucero Apr 09 '10 at 15:05
-
How to create the `yourPrincipal` object which has been passed to the `Start` method? – RBT Jul 04 '17 at 12:21
-
For me it throws error - `Unable to load DLL 'iphlpapi.dll': Exception from HRESULT: 0x80070542` while trying to run code after impersonation has come into force. – RBT Jul 06 '17 at 10:21
I have used techniques like this for impersonation with success.
The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.
The reason for doing this is to perform tasks that the current user context of an application is not allowed to do. Of course you could grant the user executing an application more privileges, but usually this is a bad idea (due to security constraints) or impossible (e.g. if you don't have full administrative access to a machine to do so).

- 36,396
- 8
- 69
- 90