Search code examples
delphidelphi-2010delphi-6

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?


Solution

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