以不同的用户身份运行代码

Vac*_*ano 35 c# impersonation windows-authentication

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

我通过PInvoke调用NetUserSetInfo,我需要将其称为不同的用户.有没有办法做到这一点?

Ric*_*erg 27

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

请注意,模仿具有重要的安全性考虑因素.确保遵循最佳做法.


Mil*_*jka 26

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

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

只需按照GithubNuget.

  • 这当然很容易实现,但我无法验证它是否有效。我做了一个 process.start("cmd.exe") 并且该进程仍然显示为启动程序的 ID 而不是模拟 ID。我可能会错过什么? (2认同)

Joh*_*nFx 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();
Run Code Online (Sandbox Code Playgroud)