```html Windows API Authentication – MSDN Community

Understanding Windows API Authentication

Posted by JaneDoe • Sep 15, 2025 • 42 replies

Question

I'm trying to integrate Windows authentication into a custom C++ application using the Win32 API. I'm particularly interested in how LogonUser, ImpersonateLoggedOnUser, and token handling work together. Can anyone provide a clear overview and some best‑practice code samples?

Answers

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;
}
Answer by EmilyR Sep 16, 2025

Don’t forget to enable the SeImpersonatePrivilege for your service account. Without it, ImpersonateLoggedOnUser will always fail with ERROR_PRIVILEGE_NOT_HELD.

Comments

```