views:

60

answers:

2

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  A: 

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.

Larry Osterman
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?
Leeks and Leaks
OpenThread takes a thread ID.
Larry Osterman
A: 

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

elder_george