我们在一个类中使用这个VB.NET代码,因为多年来测试给定用户是否为管理员(为了清晰起见,缩短了错误检查):
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As UInteger, ByVal dwLogonProvider As UInteger, ByRef phToken As IntPtr) As Boolean
Private token As IntPtr
Private identity As WindowsIdentity
Private principal As WindowsPrincipal
LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token)
identity = New WindowsIdentity(token)
principal = New WindowsPrincipal(identity)
Return principal.IsInRole(ApplicationServices.BuiltInRole.Administrator)
此代码对管理员凭据返回True。此代码适用于Windows XP,Vista和Windows 7.我们知道此代码与启用的UAC不兼容。因此,要使此代码在Windows Vista和7中运行,我们将关闭UAC。但是,在Windows 8中,即使关闭UAC,管理员凭据仍会被识别为受限令牌(BuiltInRole.User的一部分)。所以我们不能用“identity.Impersonate”冒充管理员。
为什么在Windows 8上打破了此代码的原因?
谢谢Alex
答案 0 :(得分:3)
我不知道您为什么要冒充用户来检查群组的成员资格。我认为以下内容适用于UAC开启或关闭:
Public Shared Function IsLocalAdmin(ByVal userName As String) As Boolean
Dim MyIdentity = New System.Security.Principal.WindowsIdentity(userName)
Dim MyPrincipal = New System.Security.Principal.WindowsPrincipal(MyIdentity)
Return MyPrincipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)
End Function
关闭UAC不应该是您的程序的先决条件。