Get username without name

I have a class that needs to know the name of the current user. Environment.UserName or WindowsIdentity.GetCurrent().Name for this. But when impersonation is turned on, they return the name LocalUser not the name ImpersonatedUser .

How to get the name of the current impersonated user?

The application is a C # console application, I know that impersonation is valid, since I get ImpersonatedUser privileges. Of course, I can do the impersonation code to save the given username to some global variable, but that 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 the impersonation code, but I would prefer to keep it independent of other parts of the solution.

+4
source share
2 answers

Well, it seems that the problem was the type of entry into linguistic property.

If you replace LOGON32_LOGON_NEW_CREDENTIALS (9) with LOGON32_LOGON_INTERACTIVE (2) in the impersonality code, everything works fine - WindowsIdentity.GetCurrent().Name and Environment.UserName both return ImpersonatedUser, as expected.

+2
source

Only this (instance member)

 WindowsIdentity.Name 

http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx

You do not even need to call Impersonate ().

EDIT

Without access or knowledge of impersonation,

 WindowsIdentity.GetCurrent(false).Name (same as) WindowsIdentity.GetCurrent().Name 

must work. http://msdn.microsoft.com/en-us/library/x22bbxz6.aspx

false to return the WindowsIdentity of the thread if it impersonates itself, or the WindowsIdentity of the thread if the thread is not currently impersonated.


If you used LOGON32_LOGON_NEW_CREDENTIALS, keep in mind that ( http://www.pcreview.co.uk/forums/logonuser-issues-t1385578.html ) the logged in context remains unchanged, and the second token is created for remote resources - therefore your the name WindowsIdentity.Name remains unchanged - in fact, it is still correct, since you did not really impersonate an identity, all that you have is a token for accessing resources as a secondary identifier, and the entire program / thread still running under original windows id.
+5
source

Source: https://habr.com/ru/post/1341790/


All Articles