Impersonate User

posted 23 Sep 2010, 18:33 by Delphi Basics
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:

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
Comments