模擬過程
名稱空間提供必要的API。 一種現代有效的方法利用了System.Security.Principal
。此方法採用用戶令牌句柄和一個包含在模仿用戶上下文下運行的代碼的代表(或lambda表達式)。 WindowsIdentity.RunImpersonated
>
<code class="language-csharp">WindowsIdentity.RunImpersonated(userHandle, () => { // Code executed as the impersonated user });</code>
>訪問用戶憑據
>雖然可以使用本機Win32LogonUser
API使用用戶名和密碼來獲取用戶帳戶的令牌,但強烈建議使用託管包裝器(例如
<code class="language-csharp">using SimpleImpersonation; var credentials = new UserCredentials(domain, username, password); using SafeAccessTokenHandle userHandle = credentials.LogonUser(LogonType.Interactive);</code>
重要的考慮和局限性>
模仿本質上僅限於本地機器。 訪問遠程計算機上的資源必須使這兩個機器都位於同一域內或共享信任關係。 這種方法不適合在無域系統上模仿用戶。>
以上是我如何在.NET應用程序中模仿用戶?的詳細內容。更多資訊請關注PHP中文網其他相關文章!