LogonUser function
The LogonUser function attempts to log a user on to the local computer. The function authenticates the user, and, if successful, returns a handle to an access token that represents the logged-on user.
Syntax
BOOL LogonUserA(
LPCSTR lpszUsername,
LPCSTR lpszDomain,
LPCSTR lpszPassword,
DWORD dwLogonType,
DWORD dwLogonProvider,
PHANDLE phToken
);
BOOL LogonUserW(
LPCWSTR lpszUsername,
LPCWSTR lpszDomain,
LPCWSTR lpszPassword,
DWORD dwLogonType,
DWORD dwLogonProvider,
PHANDLE phToken
);
Parameters
| Name | Type | Description |
|---|---|---|
| lpszUsername | LPCSTR/W | Pointer to a null-terminated string that specifies the name of the user. |
| lpszDomain | LPCSTR/W | Pointer to a null-terminated string that specifies the domain or local computer name. |
| lpszPassword | LPCSTR/W | Pointer to a null-terminated string that specifies the password. |
| dwLogonType | DWORD | Type of logon operation. See table below. |
| dwLogonProvider | DWORD | Logon provider. Usually LOGON32_PROVIDER_DEFAULT. |
| phToken | PHANDLE | Pointer to a handle that receives the token. |
Logon type values
| Constant | Value | Meaning |
|---|---|---|
| LOGON32_LOGON_INTERACTIVE | 2 | Logon by user with interactive logon rights. |
| LOGON32_LOGON_NETWORK | 3 | Network logon, no profile loaded. |
| LOGON32_LOGON_BATCH | 4 | Batch logon for scheduled tasks. |
| LOGON32_LOGON_SERVICE | 5 | Logon for service accounts. |
| LOGON32_LOGON_UNLOCK | 7 | Unlock workstation. |
Return value
If the function succeeds, the return value is non‑zero. If it fails, the return value is zero. Call GetLastError for extended error information.
Remarks
- The caller must have the
SE_TCB_NAMEprivilege to call this function withLOGON32_LOGON_SERVICEorLOGON32_LOGON_BATCH. - The token returned by
LogonUsercan be used withImpersonateLoggedOnUserorCreateProcessAsUser. - Use
LogonUserWfor Unicode support. Prefer the wide version in new code. - When logging on with
LOGON32_LOGON_INTERACTIVE, the user profile is loaded. This may affect performance.
Example
#include <windows.h>
#include <stdio.h>
int main()
{
HANDLE hToken = NULL;
BOOL ok = LogonUserA(
"UserName", // user name
"Domain", // domain or local computer
"Password123", // password
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&hToken);
if (ok) {
printf("Logon successful. Token: %p\n", hToken);
CloseHandle(hToken);
} else {
printf("Logon failed. Error: %lu\\n", GetLastError());
}
return 0;
}