Home >Backend Development >C++ >How to Run a .NET Process as a Different User Using Impersonation?
Through simulation, you can start the process with administrator privileges. Impersonation allows a process to run as a different user with elevated privileges.
The code you provide utilizes the ImpersonationHelper
class to impersonate a user with the required credentials. This class establishes an access token and impersonates the specified user, granting the process the necessary permissions to run as administrator.
<code class="language-csharp">public ImpersonationHelper(string domain, string user, string password) { // 调用 LogonUser 获取访问令牌的句柄。 bool returnValue = LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref m_tokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } // 模拟 m_impersonatedUser = new WindowsIdentity(m_tokenHandle).Impersonate(); }</code>
Within the using
block, activate the simulation. Subsequently, the Process
class is used to start a new process with the specified filename as argument.
<code class="language-csharp">using (new ImpersonationHelper("xxx.blabla.com", "xxxx", "xxxx")) { if (!string.IsNullOrEmpty(txtFilename.Text)) Process.Start(txtFilename.Text); }</code>
Alternatively, you can start the process as a different user by manually setting the StartInfo
attribute as follows:
<code class="language-csharp">System.Diagnostics.Process proc = new System.Diagnostics.Process(); System.Security.SecureString ssPwd = new System.Security.SecureString(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = "filename"; proc.StartInfo.Arguments = "args..."; proc.StartInfo.Domain = "domainname"; proc.StartInfo.UserName = "username"; string password = "用户输入的密码"; for (int x = 0; x < password.Length; x++) { ssPwd.AppendChar(password[x]); } password = ""; proc.StartInfo.Password = ssPwd; proc.Start();</code>
By providing SecureString
for the password, you ensure that the password is handled securely and is not stored in clear text memory.
The above is the detailed content of How to Run a .NET Process as a Different User Using Impersonation?. For more information, please follow other related articles on the PHP Chinese website!