問(wèn)題描述
這是 SQL Server 2008 R2,.NET 4.0.
This is SQL Server 2008 R2, .NET 4.0.
在我的 SQL Server 中,有一個(gè)使用Windows 身份驗(yàn)證"創(chuàng)建的用戶(hù).用戶(hù)存在于 Active Directory 域中.
In my SQL Server there is a user created with "Windows Authentication". The user exists in a Active Directory domain.
我想讓一個(gè) .NET 應(yīng)用程序以這個(gè)用戶(hù)的身份連接到 SQL Server.在應(yīng)用程序內(nèi)部,我知道用戶(hù)的域、登錄名和密碼,并且應(yīng)用程序可以訪問(wèn) AD 服務(wù)器.
I want to make a .NET application connect to the SQL Server as this user. Inside the application, I know the user's domain, login and password, and the application has network access to the AD server.
我怎樣才能做到這一點(diǎn)?
How can I accomplish this?
我知道 ASP.NET 有它的 AD 提供程序和模擬.但我正在尋找的是一個(gè)真正通用的解決方案,它應(yīng)該適用于普通的控制臺(tái)應(yīng)用程序.我可以在控制臺(tái)應(yīng)用、Windows 窗體、asp.net 或通用業(yè)務(wù)類(lèi)庫(kù)上使用的東西.
I know that ASP.NET has it's AD provider and impersonation. But what I'm looking for is a really generic solution, one that should work on a plain console application. Something that I could use on console app, windows forms, asp.net, or a common business class library.
感謝您的幫助!
推薦答案
我已經(jīng)使用這個(gè)類(lèi)完成了:
I've done it using this class:
https://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials/
如果計(jì)算機(jī)不屬于域,您必須使用 LOGON32_LOGON_NEW_CREDENTIALS = 9 進(jìn)行模擬.
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.
警告:注意連接池.該池與運(yùn)行應(yīng)用程序的實(shí)際用戶(hù)相關(guān)聯(lián),而不是與模擬的網(wǎng)絡(luò)憑據(jù)相關(guān)聯(lián).因此,在使用相同的連接字符串進(jìn)行后續(xù)訪問(wèn)時(shí),池可能會(huì)返回先前模擬的用戶(hù)建立的連接,即使您通過(guò)網(wǎng)絡(luò)模擬第二個(gè)用戶(hù).如果您不知道自己在做什么,請(qǐng)?jiān)谑褂盟鼤r(shí)禁用連接池.
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.
這篇關(guān)于ADO.NET - 使用應(yīng)用程序提供的登錄名和密碼通過(guò) Windows 登錄連接到 SQL Server的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!