Answer by JohnSmith Sep 15, 2025
Below is a minimal example that logs on a user and runs a function under that security context.
#include <windows.h>
#include <iostream>
bool RunAsUser(LPCWSTR user, LPCWSTR domain, LPCWSTR pass)
{
HANDLE token = nullptr;
if (!LogonUserW(user, domain, pass,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&token))
{
std::wcerr << L"LogonUser failed: " << GetLastError() << std::endl;
return false;
}
if (!ImpersonateLoggedOnUser(token))
{
std::wcerr << L"ImpersonateLoggedOnUser failed: " << GetLastError() << std::endl;
CloseHandle(token);
return false;
}
// *** Code that runs under the impersonated user ***
std::wcout << L"Running as impersonated user." << std::endl;
RevertToSelf();
CloseHandle(token);
return true;
}