I have a class that needs to know name of a user currently in effect. Environment.UserName
or WindowsIdentity.GetCurrent().Name
is for that. But when impersonation is enabled, they return LocalUser
name not the ImpersonatedUser
name.
How to get name of currently impersonated user?
The app is C# console application, I know that impersonation is in effect since I get priviledges of ImpersonatedUser
. Sure I can make impersonation code save impersonated username to some global variable, but it would be wrong.
UPDATE:
Impersonation code:
if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS/*=9*/, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
// WindowsIdentity.GetCurrent().Name equals "LocalUser"
// while userName equals "ImpersonatedUser"
...
I have control over impersonation code, but I would prefer to keep it independant from other parts of solution.
User impersonation allows you to temporarily sign in as a different user in your network. Users with full impersonation permissions can impersonate all other users in their network and take any action, regardless of the impersonating user's own permission level. Impersonators appear as themselves in the change history.
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.
To impersonate another user, the impersonator selects the Impersonate icon on the far right of the Tab Bar and selects the user from the Impersonate drop-down list. To stop impersonating a user, the impersonator clicks the Impersonate icon and selects Stop Impersonate from the Impersonate drop-down list.
To impersonate another user you must first retrieve the security information of the user you want to impersonate, cache that information in a security context structure, and then later use the information in the security context structure to send the impersonated messages.
Just this (instance member)
WindowsIdentity.Name
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx
You don't even have to have called Impersonate().
Without access or knowledge of the impersonation,
WindowsIdentity.GetCurrent(false).Name
(same as)
WindowsIdentity.GetCurrent().Name
should work. http://msdn.microsoft.com/en-us/library/x22bbxz6.aspx
false to return the WindowsIdentity of the thread if it is impersonating or the WindowsIdentity of the process if the thread is not currently impersonating.
original
Windows Identity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With