A Simple Impersonation Program Example
The following example shows simple impersonation using ImpersonateLoggedOnUser().
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
int wmain(int argc, WCHAR **argv)
{
// Handle to token
HANDLE hToken;
// Open a handle to the access token for the
// calling process that is the currently login access token
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken))
{
wprintf(LOpenProcessToken()-Getting the handle to access token failed, error %u\n, GetLastError());
}
else
wprintf(LOpenProcessToken()-Got the handle to access token!\n);
// Lets the calling process impersonate the security context of a logged-on user.
if(ImpersonateLoggedOnUser(hToken))
wprintf(LImpersonateLoggedOnUser() is OK.\n);
else
{
wprintf(LImpersonateLoggedOnUser() failed, error %u.\n, GetLastError());
exit(-1);
}
/////////////////
// TODO: Do other desired tasks
//////////////////
// Terminates the impersonation of a client.
if(RevertToSelf())
wprintf(LImpersonation was terminated.\n);
// Close the handle
if(CloseHandle(hToken))
wprintf(LHandle to an access token was closed.\n);
else
wprintf(LFailed to close the hToken handle! error %u\n, GetLastError());
return 0;
}
Build and run the project. The following screenshot is a sample output.