連接的模擬和認證

適用於: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。

下列範例示範如何使用 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;  
}  

注意

如需模擬中行為變更的相關資訊,請參閱2016 SQL Server 中 Database Engine 功能的重大變更

此外,如果您已取得 Microsoft Windows 身分識別實例,根據預設,您無法將該實例傳播到另一部電腦;Windows 安全性基礎結構預設會限制該基礎結構。 但是,有一項機制稱為「委派」,它可啟用多部受信任電腦之間的 Windows 識別傳播。 您可以在 TechNet 文章「Kerberos 通訊協定轉換和限制委派」中深入瞭解委派。

另請參閱

SqlContext 物件