且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ADO.NET - 使用应用程序提供的登录名和密码使用 Windows 登录连接到 SQL Server

更新时间:2023-02-04 10:07:00

我已经使用这个类完成了:

I've done it using this class:

https://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials/

如果计算机不属于域,您必须使用 LOGON32_LOGON_NEW_CREDENTIALS = 9 进行模拟.

You must impersonate using LOGON32_LOGON_NEW_CREDENTIALS = 9 if the computer does not belong to the domain.

一旦被模拟,然后使用Integrated Security=true"连接到 SQL.在 SQL 连接字符串上.

Once impersonated, then connect to SQL using "Integrated Security=true" on the SQL Connection String.

SqlConnection conn;
using (new Impersonator("myUserName", "myDomain", "myPassword", LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_DEFAULT))
{
    conn = new SqlConnection("Data Source=databaseIp;Initial Catalog=databaseName;Integrated Security=true;");
    conn.Open();
}
//(...) use the connection at your will.
//Even after the impersonation context ended, the connection remains usable.