4

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?

RRUZ
  • 134,889
  • 20
  • 356
  • 483
Johny
  • 419
  • 4
  • 15
  • So, user B is running the application, but the application needs to access a resource that only user A can access? There may be a way to mimic permissions in code, but I imagine a better practice would be to have a separate service which runs with elevated permissions (a specific service account) where that service is what actually accesses the resource(s) in question. Then the application would access that service to get what it needs. – David Jun 12 '13 at 11:50
  • I need the data folder to be accesible ONLY through my application. Running a service in the background would grant access rights to that folder at all times. – Johny Jun 12 '13 at 12:00
  • 1
    @Khatchig Through COM by using specific user, your app impersonate the user and access windows folder with user permissions. I'm not saying that is the Best solution but it will work. Only thing you need to do is to give permission to the App user in that folder. – EProgrammerNotFound Jun 12 '13 at 14:22

1 Answers1

7

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.
RRUZ
  • 134,889
  • 20
  • 356
  • 483