我有一个类需要知道当前有效的用户名。Environment.UserName
or WindowsIdentity.GetCurrent().Name
是为了那个。但是当启用模拟时,它们会返回LocalUser
名称不是ImpersonatedUser
name.
如何获取当前模拟用户的名称?
该应用程序是 C# 控制台应用程序,我知道模拟是有效的,因为我获得了以下权限ImpersonatedUser
。当然,我可以让模拟代码将模拟的用户名保存到某个全局变量中,但这是错误的。
UPDATE:
模拟代码:
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"
...
我可以控制模拟代码,但我更愿意使其独立于解决方案的其他部分。
就这个(实例会员)
WindowsIdentity.Name
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx
您甚至不必调用 Impersonate()。
EDIT
在没有访问权限或不了解冒充行为的情况下,
WindowsIdentity.GetCurrent(false).Name
(same as)
WindowsIdentity.GetCurrent().Name
应该管用。http://msdn.microsoft.com/en-us/library/x22bbxz6.aspx http://msdn.microsoft.com/en-us/library/x22bbxz6.aspx
false 则返回线程的 WindowsIdentity(如果正在模拟)或进程的 WindowsIdentity(如果线程当前未模拟)。
If you were using LOGON32_LOGON_NEW_CREDENTIALS, bear in mind that (
http://www.pcreview.co.uk/forums/logonuser-issues-t1385578.html 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)