How do I use impersonation on a C# Winforms application to run with admin privileges?

后端 未结 3 687
春和景丽
春和景丽 2020-12-15 02:03

How do I use impersonation to run a C# Winforms application with admin privileges? Can anyone throw some light on this?

3条回答
  •  轮回少年
    2020-12-15 02:28

    Following line of code may help you to achieve your goal. I found this in a "Code Project" article.

    check full article : http://www.codeproject.com/KB/dotnet/UserImpersonationInNET.aspx

    using System.Security.Principal;
    using System.Runtime.InteropServices;
    
    
    //the following code executed before you perform your task
    
    if ( ! ImpersonationUtil.Impersonate( _userName, _password, _domain ) )
    
    {
    MessageBox.Show("Impersonation failed.");
    return;
    }
    
    //Perform task as this user here...
    
    //After your task, do this:
    ImpersonationUtil.UnImpersonate();
    
    
    Here is the code for the ImpersonationUtil class:
    
    /// 
    /// Impersonate a windows logon.
    /// 
    public class ImpersonationUtil {
    
    /// 
    /// Impersonate given logon information.
    /// 
    /// Windows logon name.
    /// password
    /// domain name
    /// 
    public static bool Impersonate( string logon, string password, string
    domain ) {
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;
    
    if( LogonUser( logon, domain, password, LOGON32_LOGON_INTERACTIVE,
    LOGON32_PROVIDER_DEFAULT, ref token) != 0 ) {
    
    if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 ) {
    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
    impersonationContext = tempWindowsIdentity.Impersonate();
    if ( null != impersonationContext ) return true;
    }
    }
    
    return false;
    }
    
    /// 
    /// Unimpersonate.
    /// 
    public static void UnImpersonate() {
    impersonationContext.Undo();
    }
    
    [DllImport("advapi32.dll", CharSet=CharSet.Auto)]
    public static extern int LogonUser(
    string lpszUserName,
    String lpszDomain,
    String lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    ref IntPtr phToken );
    
    [DllImport("advapi32.dll",
    CharSet=System.Runtime.InteropServices.CharSet.Aut o,
    SetLastError=true)]
    public extern static int DuplicateToken(
    IntPtr hToken,
    int impersonationLevel,
    ref IntPtr hNewToken );
    
    private const int LOGON32_LOGON_INTERACTIVE = 2;
    private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
    private const int LOGON32_PROVIDER_DEFAULT = 0;
    private static WindowsImpersonationContext impersonationContext;
    }
    

提交回复
热议问题