模拟过程
名称空间提供必要的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中文网其他相关文章!