Impersonate User

Post date: Sep 24, 2010 1:33:28 AM

This code details how to impersonate a logged on user. The ImpersonateLoggedOnUser function lets the calling thread impersonate the security context of a logged-on user. The user is represented by a token handle. The impersonation lasts until the thread exits or until it calls the RevertToSelf api.

Read more:

ImpersonateLoggedOnUser http://msdn.microsoft.com/en-us/library/aa378612(VS.85).aspx

RevertToSelf http://msdn.microsoft.com/en-us/library/aa379317(v=VS.85).aspx

Author: Michael Puff

const
  USER              = 'UserName';
  PW                = 'Password';
function GetCurrUserName: string;
var
  Size              : DWORD;
begin
  Size := MAX_COMPUTERNAME_LENGTH + 1;
  SetLength(Result, Size);
  if GetUserName(PChar(Result), Size) then
    SetLength(Result, Size)
  else
    Result := '';
end;
function Impersonate(const User, PW: string): Boolean;
var
  LogonType         : Integer;
  LogonProvider     : Integer;
  TokenHandle       : THandle;
  strAdminUser      : string;
  strAdminDomain    : string;
  strAdminPassword  : string;
begin
  LogonType := LOGON32_LOGON_INTERACTIVE;
  LogonProvider := LOGON32_PROVIDER_DEFAULT;
  strAdminUser := USER;
  strAdminDomain := '';
  strAdminPassword := PW;
  Result := LogonUser(PChar(strAdminUser), nil,
    PChar(strAdminPassword), LogonType, LogonProvider, TokenHandle);
  if Result then
  begin
    Result := ImpersonateLoggedOnUser(TokenHandle);
  end;
end;

Usage:

 if Impersonate(USER, PW) then
  begin
    ShowMessage(GetCurrUserName);
    RevertToSelf;
    ShowMessage(GetCurrUserName);
  end