Windows Access Control List (ACL) Example 31






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.


Log on a user to a machine Program Example: Creating new C++ Win32 console mode application project


Then, add the source file and give it a suitable name.


Log on a user to a machine Program Example: Adding the C++ source file for the source code


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(L"OpenProcessToken()-Getting the handle to access token failed, error %u\n", GetLastError());



            wprintf(L"OpenProcessToken()-Got the handle to access token!\n");


      // Lets the calling process impersonate the security context of a logged-on user.


            wprintf(L"ImpersonateLoggedOnUser() is OK.\n");



            wprintf(L"ImpersonateLoggedOnUser() failed, error %u.\n", GetLastError());





      // TODO: Do other desired tasks



      // Terminates the impersonation of a client.


            wprintf(L"Impersonation was terminated.\n");


      // Close the handle


            wprintf(L"Handle to an access token was closed.\n");


            wprintf(L"Failed to close the hToken handle! error %u\n", GetLastError());


      return 0;



Build and run the project. The following screenshot is a sample output.


Log on a user to a machine Program Example: A sample console output





< Windows ACL Example 30 | Windows Access Control List (ACL) Main | Win32 Programming | Windows ACL Example 32 >