39

有没有办法告诉我的代码以不同的用户身份运行?

我正在通过 PInvoke 调用 NetUserSetInfo,我需要以不同用户的身份调用它。有没有办法做到这一点?

4

3 回答 3

30

模拟需要调用一些本机 API(即 LogonUser),因此可能不值得发布 3 页包装代码。此页面有一个完整的工作示例: http: //platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

请注意,模拟具有重要的安全考虑。确保您遵循最佳实践。

于 2009-07-22T22:17:35.373 回答
30

到目前为止,我见过的最好和最干净的代码可能是这样的:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
});

只需关注GithubNuget 即可

于 2015-05-26T18:48:40.200 回答
11

这篇文章非常简洁地解释了它:

这是文章中的代码片段:

IntPtr accessToken = IntPtr.Zero;
....
//You have to initialize your accessToken with API calling 
....
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
// Now your code is using the new WindowsLogin and you can do what ever this login can do
...

//Now you can return to your current login of Windows
context.Undo();
于 2009-07-22T22:13:52.263 回答