I am using @MattJohnson's technique for impersonating a new user using C# on .NET 4.0 on a Windows 2008 R2 domain, as described here. I manage to log on the user successfully, and the call to WindowsIdentity.Impersonate()
runs silently, returning an apparently valid context. However, when I check the last error number by using Marshal.GetLastWin32Error()
right after this, I get the value 1008 aka ERROR_NO_TOKEN.
If I let my code run, it behaves as the new user is logged on (i.e. Environment.UserName
returns the new user's name) until I dispose of the handle; however, no impersonation occurs, because the access rights of my code are still those of the original user.
I have spent some time googling about this, but I found no conclusive answer as why WindowsIdentity.Impersonate()
may cause an ERROR_NO_TOKEN error, or how to overcome it. Any ideas? Thank you.
EDIT. I just found out about the following. When I run Visual Studio normally, my code behaves as described above. However, when I run Visual Studio as an admin (i.e. right-click, Run as Administrator), then impersonation works perfectly, although I still get ERROR_NO_TOKEN from Marshal.GetLastWin32Error()
. I might as well ignore this error code since impersonation works, but I would need to run my code with elevated privileges. Isn't this odd?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…