Get impersonated user name

痴心易碎 提交于 2019-12-12 08:04:54

问题


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.


回答1:


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.


回答2:


Ok, it appears that problem was in propert impersonalization logon type.

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



来源:https://stackoverflow.com/questions/5153161/get-impersonated-user-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!