2012-01-17 4 views
2

암호화 된 .config 파일에서 제공하는 제한된 관리자 계정의 자격 증명을 사용하여 폴더를 만들려고합니다. 이제는 사용자가이 디렉터리에 액세스 할 수 없다는 가정하에 코드가 실행됩니다. 코드에 액세스 할 때 권한이 부여되지 않은 예외가 발생하므로 코드가 작동하지만 보안을 손상시킬 수는 없습니다. 암호화 된 파일에서 내 사용자 이름/암호를 얻는 방법을 이미 알고 있습니다. 가장하는 라이브러리 또는 구문에 대해 확실하지 않습니다. 이건 내 코드입니다 :가장을 사용하여 Windows 폴더 만들기

//set the cursor 

string activeDir = "\\\\department\\shares\\users\\"; 

//create directory with userID as the folder name 

string newPath = System.IO.Path.Combine(activeDir + userID); 

System.IO.Directory.CreateDirectory(newPath); 

그래서 난 자격 증명을 제공하는 방법이 필요하지만 난 내가 변경을위한 사용자 이름/암호를 입력 System.DirectoryServices.AccountManagement과 pricipalcontext를 사용하여 봤는데 loss-에 있어요 활성 디렉토리에 ... 비슷한 라이브러리를 사용하여 파일 시스템을 변경해야합니까? 도움을 주시면 감사하겠습니다.

답변

5

이 작업을 수행하는 스레드에 대해 해당 사용자를 일시적으로 가장 할 수 있다고 생각합니다. 이 작업은 P/Invoke에서만 수행 할 수 있습니다. this example을보십시오. 완전성을 위해서 (링크가 언젠가 작동을 중지하는 경우), (Jon Cole 학점) 아래 ImpersonatedUser 클래스를 찾을 들어

using (var impersonation = new ImpersonatedUser(decryptedUser, decryptedDomain, decryptedPassword)) 
{ 
    Directory.CreateDirectory(newPath); 
} 

:

using System; 
using System.ComponentModel; 
using System.Runtime.InteropServices; 
using System.Security.Principal; 

public class ImpersonatedUser : IDisposable 
{ 
    IntPtr userHandle; 

    WindowsImpersonationContext impersonationContext; 

    public ImpersonatedUser(string user, string domain, string password) 
    { 
     userHandle = IntPtr.Zero; 

     bool loggedOn = LogonUser(
      user, 
      domain, 
      password, 
      LogonType.Interactive, 
      LogonProvider.Default, 
      out userHandle); 

     if (!loggedOn) 
      throw new Win32Exception(Marshal.GetLastWin32Error()); 

     // Begin impersonating the user 
     impersonationContext = WindowsIdentity.Impersonate(userHandle); 
    } 

    public void Dispose() 
    { 
     if (userHandle != IntPtr.Zero) 
     { 
      CloseHandle(userHandle); 

      userHandle = IntPtr.Zero; 

      impersonationContext.Undo(); 
     } 
    } 

    [DllImport("advapi32.dll", SetLastError = true)] 
    static extern bool LogonUser(

     string lpszUsername, 

     string lpszDomain, 

     string lpszPassword, 

     LogonType dwLogonType, 

     LogonProvider dwLogonProvider, 

     out IntPtr phToken 

     ); 

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

    enum LogonType : int 
    { 
     Interactive = 2, 
     Network = 3, 
     Batch = 4, 
     Service = 5, 
     NetworkCleartext = 8, 
     NewCredentials = 9, 
    } 

    enum LogonProvider : int 
    { 
     Default = 0, 
    } 

} 
+0

감사합니다,이 트릭을했다. – DaneEdw

0

를 사용하여 Windows 네트워킹 (WNET) 기능. Windows 2000 이상에서 지원됩니다. 래퍼 :

public class WNet 
{ 
    public static void AddConnection(string resource, string username, string password) 
    { 
     NETRESOURCE nr = new NETRESOURCE(); 
     nr.RemoteName = resource; 
     uint err = WNetAddConnection2W(ref nr, password, username, 0); 
     if (err != 0) 
      throw new RemoteDirectoryException(string.Format("WNetAddConnection2 failed with error: #{0}", err)); 
    } 

    private struct NETRESOURCE 
    { 
     public uint Scope; 
     public uint Type; 
     public uint DisplayType; 
     public uint Usage; 
     public string LocalName; 
     public string RemoteName; 
     public string Comment; 
     public string Provider; 
    } 

    [DllImport("mpr.dll", CharSet = CharSet.Unicode)] 
    private extern static uint WNetAddConnection2W(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags); 
} 

리소스에 대한 연결을 추가 및 생성 디렉토리 :이 문서에 저를 선도하기위한

string activeDir = "\\\\department\\shares\\users\\"; 
string username = "username"; 
string password = "password"; 

WNet.AddConnection(activeDir, username, password); 

string newPath = System.IO.Path.Combine(activeDir, userID); 
System.IO.Directory.CreateDirectory(newPath); 
관련 문제