将Windows用户名/密码验证为具有管理员权限

时间:2014-06-19 22:05:21

标签: .net vb.net windows windows-authentication

我正在编写一个从非特权用户帐户运行的Windows窗体应用程序。

对于一个操作,我需要提示输入具有Admin privs的帐户的用户名/密码。

因此,应用程序实际上不必从特权帐户运行;但是用户必须指定管理员帐户才能被允许执行某些操作。

有没有人知道如何验证用户名/密码作为具有管理员权限的帐户?

1 个答案:

答案 0 :(得分:2)

正如Harry Johnston评论的那样,您可以使用以下内容来验证用户名/密码:

Private Declare Auto Function CloseHandle Lib "kernel32.dll"   
                             (ByVal  clsTokenToClose As IntPtr) As Integer

Private Declare Auto Function LogonUser Lib "advapi32.dll" ( _
                                ByVal lpszUsername As String, _
                                ByVal lpszDomain As String, _
                                ByVal lpszPassword As String, _
                                ByVal dwLogonType As Integer, _
                                ByVal dwLogonProvider As Integer, _
                                ByRef phToken As IntPtr) As Boolean

Const DOMAIN_NAME As String = "MYDOMAIN"
Dim token As IntPtr

'Use the Win32API LogonUser to authenticate UserName and Password.
'If successful, a token representing the user is returned.

 If LogonUser("UserName", DOMAIN_NAME, "password", LOGON32_LOGON_BATCH,  
              LOGON32_PROVIDER_DEFAULT, token) Then

     'The token is used to create a WindowsIdentity, which is in turn
     'used to create a WindowsPrincipal.  The WindowsPrincipal is checked
     'to see if it belongs to the desired group in ActiveDirectory.

     Dim WIdent As New WindowsIdentity(token)

     Dim WPrincipal As New WindowsPrincipal(WIdent)

     If WPrincipal.IsInRole("Administrators") Then 
        'User has admin privilege, carry on.

     End If

     CloseHandle(token)

 End If

请务必更换"管理员"在WPrincipal.IsInRole中调用您要检查的组。