我需要检查用户是否是运行该应用程序的机器上的管理员。基本上,用户可能会从另一台机器提供用户名,密码和域名。这些通过WCF传输,在这个阶段我需要验证提供的用户名,密码和域是否具有该机器的管理权限。这意味着没有必要使用WMI,因为一切都是在本地发生的(用户只需通过WCF发送用户名,密码,域作为字符串)如何检查用户是否是该机器上的管理员
用户可以位于域上,因此可以链接到Active Directory,但也可以是本地用户,这意味着我无法回复从Active Directory中查找它。
我设法模拟用户,并可以验证此用户是本地组中的管理员。我使用下面的命令测试了这个:
net localgroup administrators
我现在正在用当前模拟用户创建一个WindowsPrincipal。但是,在检查此用户是否为管理员时,我收到了错误信息。这里是重要的代码:
// obtains user token
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// creates duplicate token handle
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
if (wp.IsInRole(WindowsBuiltInRole.Administrator))
{
//is admin
}
else
{
//is not an admin (I am still getting this when user is an admin)
}
bImpersonated返回true(因此模拟工作) bRetVal也会返回true。(因此令牌是有效的)
的模拟代码是从here(除了管理员检查)
任何帮助将不胜感激。
模仿用户,然后获取活动主体,再检查'IsInRole'? – 2014-10-01 17:23:52
@PeterRitchie这看起来不错,但由于某些原因,IsInRole(WindowsBuiltInRole.Administrator)总是返回false(对于本地帐户和域帐户)。有任何想法吗? – seedg 2014-10-02 07:30:56
你有没有试过[这](http://stackoverflow.com/questions/1089046/in-net-c-test-if-user-is-an-administrative-user)? – 2014-10-02 09:58:58