【问题标题】:Run Code as a different user以其他用户身份运行代码
【发布时间】:2010-11-13 04:55:20
【问题描述】:

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

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

【问题讨论】:

    标签: c# impersonation windows-authentication


    【解决方案1】:

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

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

    只需关注GithubNuget

    【讨论】:

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

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

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

    【讨论】:

      【解决方案3】:

      article 解释得很简洁:

      这是文章中的代码 sn-p:

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

      【讨论】:

        猜你喜欢
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        • 2018-06-06
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 2019-11-09
        • 2012-02-05
        相关资源
        最近更新 更多