0

Is there a way to find out when a managed thread has changed user contexts due to impersonation? I'd like to be able to do this from unmanaged code that is observing the managed code using Microsoft's .NET Profiling APIs.

For example some managed code may be running in user context A, and then impersonate user B. The impersonation may happen due to web.config or dynamically at runtime because the managed code is using APIs to manually impersonate user B.

How can I catch the switch from user A to user B from my unmanaged thread?

2 Answers 2

3

You can't do this reliably because as far as I know there's no notification when the thread token changes.

What you CAN do is to call OpenThreadToken on the target thread. When the API succeeds (returning a token) the thread is impersonating someone. That might be sufficient.

1
  • Hmm, interesting. OpenThreadToken takes a thread handle. If my observing codepath is native, and I'm trying to track when a managed thread begins impersonating, I believe I can get the thread ID, but I'm not sure I can get the windows thread handle. How do you convert from ID to handle? Also, how would you implement your solution, by constantly polling the managed thread by calling OpenThreadToken? Sep 2, 2009 at 13:24
0

You may check Thread.CurrentPrincipal property. It returns WindowsPrincipal basing on OpenThreadToken call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.