連接的模擬和認證
在 SQL Server Common Language Runtime (CLR) 整合中,使用 Windows 驗證很複雜,但比使用SQL Server驗證更安全。 當使用 Windows 驗證時,請牢記以下的考量事項。
根據預設,連接到 Windows 的 SQL Server 處理序需要 SQL Server Windows 服務帳戶的安全性內容。 但是,可將 CLR 函數對應到 Proxy 識別,好讓它的傳出連接具有與 Windows 服務帳戶不同的安全性內容。
在某些情況下,您可能會想要使用 SqlContext.WindowsIdentity
屬性來模擬呼叫端,而不是以此服務帳戶的身分執行。 WindowsIdentity
執行個體代表叫用呼叫程式碼之用戶端的識別,而且只有當用戶端使用 Windows 驗證時才可使用。 在您取得 WindowsIdentity
執行個體之後,您可以呼叫 Impersonate
來變更執行緒的安全性 Token,然後代表用戶端開啟 ADO.NET 連接。
呼叫 SQLCoNtext.WindowsIdentity.Impersonate 之後,就無法存取本機資料,也無法存取系統資料。 若要再次存取資料,您必須呼叫 WindowsImpersonationCoNtext.Undo。
下列範例示範如何使用 SqlContext.WindowsIdentity
屬性來模擬呼叫端。
Visual C#
WindowsIdentity clientId = null;
WindowsImpersonationContext impersonatedUser = null;
clientId = SqlContext.WindowsIdentity;
// This outer try block is used to protect from
// exception filter attacks which would prevent
// the inner finally block from executing and
// resetting the impersonation.
try
{
try
{
impersonatedUser = clientId.Impersonate();
if (impersonatedUser != null)
return GetFileDetails(directoryPath);
else return null;
}
finally
{
if (impersonatedUser != null)
impersonatedUser.Undo();
}
}
catch
{
throw;
}
注意
如需模擬中行為變更的相關資訊,請參閱2014 SQL Server 中的資料庫引擎功能重大變更。
此外,如果您取得 Microsoft Windows 身分識別實例,根據預設,您無法將該實例傳播到另一部電腦;Windows 安全性基礎結構預設會限制該基礎結構。 但是,有一項機制稱為「委派」,它可啟用多部受信任電腦之間的 Windows 識別傳播。 您可以在 TechNet 文章「Kerberos 通訊協定轉換和限制委派」中深入瞭解委派。