Windows偽装は、ログインの詳細を使用してユーザートークンを取得することでこの問題を解決します。このトークンを使用してWindowsIdentityを取得し、次にそれを使用して偽装コンテキストを生成することができます。このコンテキストスコープ内で、ファイルシステムに偽装されたユーザーとしてアクセスできます。
もちろん、このアプローチを使用するには、ユーザー名とパスワードを保存する必要があります。
まず、Windowsからのユーザートークンを取得するために必要なWindows APIを定義します。
internal class WindowsAPI
{
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_LOGON_INTERACTIVE = 2;
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername,
String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
}
その後、WindowsIdentityをAQUIREこれらのAPIを使用します。
private WindowsIdentity GetIdentity(string userName, string password)
{
_userToken = IntPtr.Zero;
if (!WindowsAPI.LogonUser(
userName,
AbbGrainDomain,
password,
WindowsAPI.LOGON32_LOGON_INTERACTIVE, WindowsAPI.LOGON32_PROVIDER_DEFAULT,
ref _userToken
))
{
int errorCode = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(errorCode);
}
return new WindowsIdentity(_userToken);
}
そして最後に、このIDを使用偽装コンテキストを生成します。
public List<string> GetDirectories(string searchPath)
{
using (WindowsImpersonationContext wic = GetIdentity().Impersonate())
{
var directories = new List<string>();
var di = new DirectoryInfo(searchPath);
directories.AddRange(di.GetDirectories().Select(d => d.FullName));
return directories;
}
}
最後に、偽装コンテキストをクリーンアップすることが重要ですウィンドウはID_posableパターンを使用して、格納された_userTokenを使用して処理します。
if (_userToken != IntPtr.Zero)
WindowsAPI.CloseHandle(_userToken);
私はそれがIPrincipal –