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

ADO.NET - Connect to SQL Server with Windows Login with login and password supplied by the application

这是 SQL Server 2008 R2,.NET 4.0。

在我的 SQL 服务器中,有一个用 "Windows Authentication" 创建的用户。用户存在于 Active Directory 域中。

我想让 .NET 应用程序以该用户身份连接到 SQL 服务器。在应用程序内部,我知道用户的域、登录名和密码,并且该应用程序可以通过网络访问 AD 服务器。

我怎样才能做到这一点?

我知道 ASP.NET 有它的 AD 提供商和模拟。但我正在寻找的是一个真正通用的解决方案,一个应该在普通控制台应用程序上工作的解决方案。我可以在控制台应用程序、windows 表单、asp.net 或常见业务 class 库中使用的东西。

感谢您的帮助!

我已经用这个 class:

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

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

模拟完成后,使用 SQL 连接字符串上的“Integrated Security=true”连接到 SQL。

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.