views:

479

answers:

2

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 assume the credentials of the user that launches the connecting process.

This means that to change the login, I currently have two options:

  1. Log off and Log in as the desired user, then run my application

  2. Launch the program from the command line using the RUNAS command.

I'd like to let the user provide credentials from within the application, and log in as that user. Is this possible, either by manipulating the ConnectionString or by programatically changing the user of the current process?

The closest I've found is this entry, which tells me how to launch another process under specific credentials. I could use that technique to create a "launcher" program that launches the connecting process after gathering credentials from the user, but I'd really like something cleaner.

I'm using Delphi 2010 for this project.

Thanks

+7  A: 

I think a combination of LogonUser and then ImpersonateLoggedOnUser will do the trick for you. That should change the user account for which the current process is running. As gbn mentioned, you will likely have to disconnect any active connection before changing the logon credentials.

Scott W
probably better answer than mine. I was focusing on the DB end, rather than what you do in code.
gbn
Impersonation is for the Current THREAD only (which is an advantage is this case), if you need to handle multiple users/connections you can run them in a seperate thread.
Remko
+3  A: 

Using the method suggested by Scott W, this code worked for me. Some of this may need to be tweaked based on your specific network environment.

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;

This code can be called like so:

...
//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;
JosephStyons