I use advapi32.dll's logonuser method to access data over our network.
I know it change the thread's user to the information i give it, but i was wondering if there's a way to reverse it.
I want to access the data and then return to the local user credentials.
Asked
Active
Viewed 1,685 times
5

Ben2307
- 1,003
- 3
- 17
- 31
2 Answers
8
Some time ago I created a small impersonator class.
Basically you wrap your code to execute under another user simply inside a using
block:
using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
...
<code that executes under the new context>
...
}
Worked very well for my projects.

Uwe Keim
- 39,551
- 56
- 175
- 291
-
2You should add the code here. SO answers should be self-contained when source code can be provided (considering how small that class is, it probably can be). – Merlyn Morgan-Graham Oct 03 '11 at 10:04
-
Is this the new trend here on Stack Overflow to meta-comment? Just go search for answers with self-contained code and those without and then compare the ratio. – Uwe Keim Oct 03 '11 at 10:27
-
2I just like source code to be on SO. Didn't mean to antagonize you :) – Merlyn Morgan-Graham Oct 03 '11 at 10:38
-
3@Merlyn in this case the answer is much better as it stands because the code at code project contains multiple files and has a nice article attached. I'm upvoting this answer. – David Heffernan Oct 03 '11 at 10:46
-
2I stand corrected, guys. Good answer and an upvote for you Uwe. – Merlyn Morgan-Graham Oct 03 '11 at 18:25
1
You can call RevertToSelf
.
That said, there is something to be said for spinning up a dedicated thread for the impersonation task, and terminating it when the impersonation work is complete. This will segregate the impersonation work so that if any callbacks or messages are processed on the main thread they will be performed in the context of the principal user rather than the impersonated user. In fact, the more I think about this the stronger I feel that a dedicated thread is the solution.

David Heffernan
- 601,492
- 42
- 1,072
- 1,490