Get impersonated user name

zzandy picture zzandy · Mar 1, 2011 · Viewed 7.1k times · Source

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.

Answer

RichardTheKiwi picture RichardTheKiwi · Mar 1, 2011

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

EDIT

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.


If you were using LOGON32_LOGON_NEW_CREDENTIALS, bear in mind that (http://www.pcreview.co.uk/forums/logonuser-issues-t1385578.html) the logged in context remains unchanged while a second token is created for remote resources - this is why your WindowsIdentity.Name remains unchanged - in effect it is still correct, because you have not actually impersonated the identity, all you have is a token to access resources as the secondary identity while the entire program/thread is still running under the original Windows Identity.