適用於:SQL Server
在 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 來變更線程的安全性令牌,然後代表客戶端開啟 ADO.NET 連線。
呼叫 SQLContext.WindowsIdentity.Impersonate之後,您無法存取本機數據,而且無法存取系統數據。 若要再次存取資料,您必須呼叫 WindowsImpersonationContext.Undo。
下列 C# 範例示範如何使用 SqlContext.WindowsIdentity 屬性模擬呼叫端。
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;
}
注意
如需模擬中行為變更的相關信息,請參閱 SQL Server 2016中資料庫引擎功能的重大變更。
此外,如果您取得 Windows 身分識別實例,根據預設,您無法將該實例傳播到另一部計算機;Windows 安全性基礎結構預設會限制該基礎結構。 不過,有一種稱為 委派 機制,可跨多個受信任的計算機傳播 Windows 身分識別。 如需委派的詳細資訊,請參閱 Kerberos 通訊協定轉換和限制委派。