以不同的用户身份运行代码(C#)

问题描述:

有没有办法让我的代码以不同的用户身份运行?以不同的用户身份运行代码(C#)

我打电话NetUserSetInfo通过一个PInvoke,我需要称它为一个不同的用户。有没有办法做到这一点?

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

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

article解释它很简洁:

下面是文章的代码片段:

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(); 
+2

文章中的代码已不存在。 – 2016-12-02 14:58:42

也许最好是我迄今见过的最干净的code是这个

using (Impersonation.LogonUser(domain, username, password, logonType)) 
{ 
    // do whatever you want as this user. 
} 

只要按照GithubNuget

+1

这当然很容易实现,但我无法验证它正在工作。我做了一个process.start(“cmd.exe”),并且该进程仍然显示为启动该程序的ID所拥有的不是模拟的ID。我可能会错过什么? – 2016-10-27 18:09:37

是模仿有助于以不同的用户运行一些代码。它在我的情况下工作正常。 (感谢米兰Matějka)

我还发现了一个Ref链接。希望它可以帮助您轻松地从nuget获得包装: http://iamfixed.blogspot.de/2017/11/run-code-as-different-user-in-c-from.html