Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatical log in by providing credentials

Consider windows users A (with administrative rights) and B (restricted access rights). Also a data folder located on the server to which only user A has the access to.

The challenge I’m facing is to log in windows through user B, and through my Delphi application trying to access the data folder by providing the credentials of user A programmatically.

Is there an API function which would allow me to achieve this objective?

like image 279
Johny Avatar asked Mar 24 '23 14:03

Johny


1 Answers

You can impersonate a logged on user to access the data folder, using the LogonUser, ImpersonateLoggedOnUser and RevertToSelf functions.

Try this sample

{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

function ConnectAs(const lpszUsername, lpszPassword: string): Boolean;
var
  hToken       : THandle;
begin
  Result := LogonUser(PChar(lpszUsername), nil, PChar(lpszPassword), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, hToken);
  if Result then
    Result := ImpersonateLoggedOnUser(hToken)
  else
  RaiseLastOSError;
end;

begin
  try
   ConnectAs('Admin','Password');
   //do something here


   //terminates the impersonation
   RevertToSelf;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.
like image 193
RRUZ Avatar answered Apr 01 '23 20:04

RRUZ