开发者

Change username programmatically when connecting to a 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 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. I开发者_Go百科s 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


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.


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
RevertToSelf;

//now my process is back to normal
DoSomethingMundane;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜