c# - 在另一台机器上模拟本地用户

标签 c# dllimport impersonation

我需要将我的 Controller 登录到另一台机器上并在上面复制一个文件;我必须在远程计算机上使用本地用户。

目前我正在使用这段代码:

    private Impersonate(bool active, string domain, string username, string password, LogonType logonType)
    {
        if (active)
        {
            IntPtr handle;
            var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle);
            if (!ok)
            {
                var errorCode = Marshal.GetLastWin32Error();
                throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
            }

            _handle = new SafeTokenHandle(handle);
            _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
        }
    }

传递这些参数:

    using (Impersonate.LogonUser(true,
        ".",
        "todev1.domain.com\admin",
        "Test123_",
        LogonType.Interactive))
    {

    }  

和这个胜利 API:

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

我检查了这个 Q/A Using advapi32.dll:LogonUserA() to impersonate a remote machine's local user但提供的解决方案不起作用。

我试图将多个值作为域、用户等传递给该方法,但我找不到正确的解决方案。我尝试使用 NewCredentials,但即使未登录,它也总是返回正常。

最佳答案

我终于解决了这个问题,无需将用户添加到每台将模拟远程机器的机器。

使用NewCredential是正确的,但是使用的是WINNT50 LogonProvider。

所以我现在的模拟方法是这样的:

 private Impersonate(bool active, string domain, string username, string password, LogonType logonType, LogonProvider logonProvider)
        {
            if (active)
            {
                IntPtr handle;
                var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, (int)logonProvider, out handle);
                if (!ok)
                {
                    var errorCode = Marshal.GetLastWin32Error();
                    throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
                }

                _handle = new SafeTokenHandle(handle);
                _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
            }
        }

然后我使用代码调用 Impersonate 方法:

using (Impersonate.LogonUser(true,
    "todev1.domain.com",
    "admin",
    "Test123_",
    LogonType.NewCredentials,
    LogonProvider.WinNT50))
{

}

关于c# - 在另一台机器上模拟本地用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43722118/

相关文章:

c# - 是否可以用新的 Reactive 框架替换 C# 中的传统事件处理?

c# - 在 C# 中的两个应用程序之间共享数据成员

c# - 处理列表和 List.Take()

C# DllImport 意外崩溃

google-cloud-platform - 获取谷歌服务帐户的 signedJwt token

c# - 模拟 UNIX 用户并更新环境变量

c# - 订阅者方法与事件

c# - 在C#Windows应用程序中使用C++ DLL:获取错误 “Entry point not found”

c# - 从 C# 设置非托管 C dll 的公共(public)字段

php - Laravel-8 中 Auth::onceUsingID() 和 Auth::setUser() 有什么区别