没有 windows 服务的服务帐户(域)是否可以使用不同用户(模拟)下的 运行 代码?

Is running code under a different user (impersonation) possible with a service account (domain) without a windows service?

我们想要 运行 服务帐户上下文中的进程。 可以在没有 windows 服务的情况下使用服务用户帐户(域)模拟执行(使用 Process.Start)WPF 应用程序中的方法吗?

如果可能,如何实现?

OP:

Can a method within a WPF application be executed (using Process.Start) impersonated with a service user account (domain) without a windows service?

无论调用进程是什么类型,您都可以模拟用户。即 WPF,Windows 服务,控制台应用程序 。不要紧。但是在 Windows Vista 和更高版本上,该过程必须 运行 作为 管理员 .

示例由 MSDN

提供
string userName, domainName;
// Get the user token for the specified user, domain, and password using the
// unmanaged LogonUser method.
// The local machine name can be used for the domain name to impersonate a user on this machine.
Console.Write("Enter the name of the domain on which to log on: ");
domainName = Console.ReadLine();

Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
userName = Console.ReadLine();

Console.Write("Enter the password for {0}: ", userName);

...

// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);
...

using (safeTokenHandle)
{
...

    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
    {
        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
        {
            // Check the identity.
            Console.WriteLine("After impersonation: "
                             + WindowsIdentity.GetCurrent().Name);
        }
    }
}
 

有关更多信息和完整示例,我建议查看上面的 link,因为我不想引用整个示例。

更多