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.
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.