Функция LogonUser

Declare Function LogonUser Lib "Advapi32" Alias "LogonUserA" (ByVal _
    lpszUserName As String, ByVal lpszDomain As String, _
    ByVal lpszPassword As String, ByVal dwLogonType As Long, _
    ByVal dwLogonProvider As Long, phToken As Long) As Long

Функция LogonUser пытается зарегистрировать пользователя на локальном компьютере. Вы не можете использовать LogonUser на удаленном компьютере. Вы определяете пользователя при помощи имени пользователя (логин) и домена, и подтверждаете подлинность пользователя паролем. Если функция вызвана успешно, то вы получаете дескриптор к лексеме, которая представляет вошедшего пользователя. Вы можете тогда использовать этот дескриптор, чтобы исполнить роль указанного пользователя или, в большинстве случаев, создавать процесс, который выполняется в контексте указанного пользователя.

Возвращаемое значение

В успешном случае функция возвращает ненулевое значение. В случае ошибки функция возвращает 0 (для получения кода ошибки используйте GetLastError)

Параметры

lpszUsername
Строка, содержащая имя пользователя, под которым он входит в систему
lpszDomain
Строка, задающее домен или сервер, которые хранят учетные записи пользователя. Если параметр равен ".", то используется учетная запись с локального компьютера
llpszPassword
Строка, содержащая пароль в плоском тексте для имени пользователя lpszUsername
dwLogonType
Тип авторизации. Может принимать одно из следующих значений:
LOGON32_LOGON_BATCHThis logon type is intended for batch servers, where processes may be executing on behalf of a user without their direct intervention. This type is also for higher performance servers that process many plaintext authentication attempts at a time, such as mail or Web servers. The LogonUser function does not cache credentials for this logon type.
Const LOGON32_LOGON_INTERACTIVE = 2&This logon type is intended for users who will be interactively using the computer, such as a user being logged on by a terminal server, remote shell, or similar process. This logon type has the additional expense of caching logon information for disconnected operations; therefore, it is inappropriate for some client/server applications, such as a mail server.
Const LOGON32_LOGON_NETWORK = 3&This logon type is intended for high performance servers to authenticate plaintext passwords. The LogonUser function does not cache credentials for this logon type.
LOGON32_LOGON_NETWORK_CLEARTEXTThis logon type preserves the name and password in the authentication package, which allows the server to make connections to other network servers while impersonating the client. A server can accept plaintext credentials from a client, call LogonUser, verify that the user can access the system across the network, and still communicate with other servers. Windows NT: This value is not supported.
LOGON32_LOGON_NEW_CREDENTIALSThis logon type allows the caller to clone its current token and specify new credentials for outbound connections. The new logon session has the same local identifier but uses different credentials for other network connections. This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. Windows NT: This value is not supported.
LOGON32_LOGON_SERVICEIndicates a service-type logon. The account provided must have the service privilege enabled.
LOGON32_LOGON_UNLOCKThis logon type is for GINA DLLs that log on users who will be interactively using the computer. This logon type can generate a unique audit record that shows when the workstation was unlocked.
dwLogonProvider
Specifies the logon provider. Может принимать одно из следующих значений:
Const LOGON32_PROVIDER_DEFAULT = 0&Use the standard logon provider for the system. The default security provider is negotiate, unless you pass NULL for the domain name and the user name is not in UPN format. In this case, the default provider is NTLM. Windows 2000/NT: The default security provider is NTLM.
LOGON32_PROVIDER_WINNT50Use the negotiate logon provider. Windows NT: This value is not supported.
LOGON32_PROVIDER_WINNT40Use the NTLM logon provider.
LOGON32_PROVIDER_WINNT35Use the Windows NT 3.5 logon provider.
phToken
pointer to a handle variable that receives a handle to a token that represents the specified user. You can use the returned handle in calls to the ImpersonateLoggedOnUser function. In most cases, the returned handle is a primary token that you can use in calls to the CreateProcessAsUser function. However, if you specify the LOGON32_LOGON_NETWORK flag, LogonUser returns an impersonation token that you cannot use in CreateProcessAsUser unless you call DuplicateTokenEx to convert it to a primary token. When you no longer need this handle, close it by calling the CloseHandle function.

Пример

' Проверяем логин и пароль пользователя

Private Function CheckWindowsUser(ByVal UserName As String, _
    ByVal Password As String, Optional ByVal Domain As String) As Boolean

    Dim hToken As Long, ret As Long

    ' если домен не используется
    If Len(Domain) = 0 Then Domain = vbNullString
    ' проверяем логин/пароль
    ret = LogonUser(UserName, Domain, Password, LOGON32_LOGON_INTERACTIVE, _
        LOGON32_PROVIDER_DEFAULT, hToken)
    ' если ненулевое значение, значит ошибки нет
    If ret Then
        CheckWindowsUser = True
        CloseHandle hToken
    End If
End Function

Private Sub Command1_Click()
 MsgBox CheckWindowsUser(Text1.Text, Text2.Text)
End Sub

Смотри также

CloseHandle, CreateProcessAsUser

Категория

Доступ