2013-02-28 28 views
2

我有它承載的應用程序來寫入文件的硬盤驅動器的服務器。我有2個其他服務器B和C. B和C可以通過UNC股A.訪問複製文件跨UNC

我想寫到硬盤上以類似的目錄結構被複制到服務器B和C.我的任何文件已經嘗試使用File.Copy,但每次都會給我一個拒絕訪問。我如何設置安全措施才能使其發揮作用?或者有沒有辦法模仿用戶?

感謝

+1

可能重複:http://stackoverflow.com/questions/2702109/how-to-impersonate-a-user-for-a-file-copy-over-the-network-when-dns-or -netbios-i編輯:標記爲重複的錯誤問題,但它顯示瞭如何模擬所有相同的答案。 – 2013-02-28 19:57:51

+3

我不明白爲什麼這個問題是關閉的話題。這是關於如何在訪問UNC共享時使用網絡憑證進行身份驗證的完美問題。下面我提供了一個優雅的答案。 – 2013-03-05 23:14:30

回答

8

如果你只是想訪問需要憑據的網絡共享,可以做到以下幾點:

  1. 調用WinAPI的LogonUser的拿到了入網證書令牌。
  2. 將令牌包裝在WindowsIdentity對象中。
  3. 在WindowsIdentity上調用模擬器。
  4. 訪問網絡資源。
  5. 配置WindowsImpersonationContext和WindowsIdentity。
  6. 調用WinAPI CloseHandle。

我創造了一個實現此行爲的一次性類。

... 

    using (new NetworkImpersonationContext("domain", "username", "password")) 
    { 
     // access network here 
    } 

... 

public class NetworkImpersonationContext : IDisposable 
{ 
    private readonly WindowsIdentity _identity; 
    private readonly WindowsImpersonationContext _impersonationContext; 
    private readonly IntPtr _token; 
    private bool _disposed; 

    public NetworkImpersonationContext(string domain, string userName, string password) 
    { 
     if (!LogonUser(userName, domain, password, 9, 0, out _token)) 
      throw new Win32Exception(); 
     _identity = new WindowsIdentity(_token); 
     try 
     { 
      _impersonationContext = _identity.Impersonate(); 
     } 
     catch 
     { 
      _identity.Dispose(); 
      throw; 
     } 
    } 

    #region IDisposable Members 

    public void Dispose() 
    { 
     GC.SuppressFinalize(this); 
     Dispose(true); 
    } 

    #endregion 

    [DllImport("advapi32.dll", SetLastError = true)] 
    private static extern bool LogonUser(
     string lpszUsername, 
     string lpszDomain, 
     string lpszPassword, 
     int dwLogonType, 
     int dwLogonProvider, 
     out IntPtr phToken 
     ); 

    [DllImport("kernel32.dll", SetLastError = true)] 
    private static extern bool CloseHandle(IntPtr hHandle); 

    protected virtual void Dispose(bool disposing) 
    { 
     if (_disposed) 
      return; 
     _disposed = true; 

     if (disposing) 
     { 
      _impersonationContext.Dispose(); 
      _identity.Dispose(); 
     } 

     if (!CloseHandle(_token)) 
      throw new Win32Exception(); 
    } 

    ~NetworkImpersonationContext() 
    { 
     Dispose(false); 
    } 
} 
2

我不會嘗試,並在C#中解決這個。目前已經有很多文件複製產品,其中包括內置於Windows Server 2003及更高版本中的DFS Replication

0

我不會試圖編程安全支持這一點。你最好的選擇是用Windows配置它(假設你使用的是Windows服務器)。您必須確保服務器B和C具有分配的權限,以允許服務器A寫入UNC共享。

在這一點上,假設這是Windows中,你可以分配權限給服務器B和C的機器名,或者你可以把服務器B &ç成團,並分配權限給該組服務器A上