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(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.

 

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 >