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

标签 c# wpf impersonation

我们想在服务帐户的上下文中运行一个进程。
可以在没有 Windows 服务的情况下使用服务用户帐户(域)来执行(使用 Process.Start)WPF 应用程序中的方法吗?
如果可能,如何实现?

最佳答案

操作:

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);
        }
    }
}
 
更多信息和完整示例 ,我建议查看上面的链接,因为我不想引用整个示例。
更多的
  • WindowsImpersonationContext Class
  • Impersonating and Reverting
  • 关于c# - 是否可以使用没有 Windows 服务的服务帐户(域)在不同用户(模拟)下运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62933833/

    相关文章:

    c# - Entity Framework 7 和 SQLite 的组合键

    c# - 正则表达式以确保在诸如 "05123:12315"的字符串中,第一个数字小于第二个数字?

    c# - 在文件扩展名 C# 之前将字符串插入到文件路径字符串中

    c# - 使用 IValueConverter 验证可为 null int

    c# - 如何以编程方式将绑定(bind)转换器添加到 WPF ListView?

    c# - 如何在 C# 中将文件保存在同一网络中的另一台机器上?

    asp.net - 无法在 ASP.NET 站点上使用模拟删除共享中的文件

    c# - <identity impersonate ="true"/>的正确使用

    c# - C# 中 C++ 程序员的指针替代

    c# - 如何在 C# 中生成 8 位唯一和随机数