Change username programmatically when connecting to a Sql Server using Windows authentication from a Delphi application

坚强是说给别人听的谎言 提交于 2019-12-08 09:45:19

问题


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


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/1841978/change-username-programmatically-when-connecting-to-a-sql-server-using-windows-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!