且构网

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

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

更新时间:2023-02-04 09:53:10

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

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.

一旦被模拟,然后使用 SQL 连接字符串上的Integrated Security=true"连接到 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.

警告:注意连接池.该池与运行应用程序的实际用户相关联,而不是与模拟的网络凭据相关联.因此,在使用相同的连接字符串进行后续访问时,池可能会返回先前模拟的用户建立的连接,即使您通过网络模拟第二个用户.如果您不知道自己在做什么,请在使用它时禁用连接池.

ALERT: Beware of connection pooling. The pool is associated with the actual user running the application, not with the network credentials that were impersonated. So on subsequent access using the same connection string, the pool may return a connection made by a previously impersonated user, even if you netorkly-impersonate a second user. If you don't know what you're doing, disable connection pooling when using this.