Changing username programmatically when connecting to an Sql server using Windows authentication from a Delphi application

I have a Sql server that uses windows authentication.

I want to connect to the server from a Delphi application.

By default, SQL Server will accept the credentials of the user starting the connection process.

This means that I have two options for changing the login:

  • Log out and log in as your desired user, then launch my application

  • Run the program from the command using the RUNAS command.

I want the user to provide credentials from the application and register as that user. Is this possible by manipulating ConnectionString or programmatically changing the user of the current process?

The closest I found this entry , which tells how to start another process under specific permissions. I could use this technique to create a launcher program that starts the connection process after collecting user credentials, but I would really like something cleaner.

I am using Delphi 2010 for this project.

thank

0
source share
2 answers
+7

, W, . , .

procedure ChangeLoggedInUser(username, password, domain: string);
var
  creds: Cardinal;
begin
  try
    if LogonUser(PChar(username)
        ,PChar(domain)
        ,PChar(password)
        ,LOGON32_LOGON_NETWORK
        ,LOGON32_PROVIDER_DEFAULT
        ,creds
      )
    then begin
      ImpersonateLoggedOnUser(creds);
    end
    else begin
      RaiseLastOSError;
    end;
  finally
    //wipe the memory for security
    FillChar(username,SizeOf(username),#0);
    FillChar(password,SizeOf(username),#0);
    FillChar(domain,SizeOf(username),#0);
  end;  //try-finally
end;

:

...
//at this point i am logged in as whoever is logged into the local machine
DoSomethingMundane;

//change credentials of the current thread
ChangeLoggedInUser('importantuser','secretpassword','mydomain');

//now my process will be logged in as "importantuser"
DoSomethingThatRequiresCreds;

//go back to normal
ReverToSelf;

//now my process is back to normal
DoSomethingMundane;
+3

All Articles