Search code examples
c#impersonationusing-statement

passing code to a function as parameter within "using statement"


This code works fine with me:

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    [DllImport("kernel32.dll")]
    public static extern bool CloseHandle(IntPtr token);

enum LogonType
    {
        Interactive = 2,
        Network = 3,
        Batch = 4,
        Service = 5,
        Unlock = 7,
        NetworkClearText = 8,
        NewCredentials = 9
    }
    enum LogonProvider
    {
        Default = 0,
        WinNT35 = 1,
        WinNT40 = 2,
        WinNT50 = 3
    }

private void Button1_Click()
    { 
        IntPtr token = IntPtr.Zero;
        LogonUser("Administrator",
                  "192.168.1.244",
                  "PassWord",
                  (int)LogonType.NewCredentials,
                  (int)LogonProvider.WinNT50,
                  ref token);
        using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token))
        {
    CloseHandle(token);
    /*
    Code_of_Do_Something
    */
    }
}

BUT...This means I have to repeat the last code which inside "Button1_Click()" each time I need to do impersonation ( Doing something on the remote machine = server). So my question: Is it possible to do something like this illustration?: enter image description here


Solution

  • Yes, it is possible to pass code as a parameter. But let's solve your problem without using lambdas:

    private void Button1_Click()
    {
        using(GetImpersonationContext())
        {
            /* code here */
        } 
    }
    private WindowsImpersonationContext GetImpersonationContext()
    {
        IntPtr token = IntPtr.Zero;
        LogonUser("Administrator",
                  "192.168.1.244",
                  "PassWord",
                  (int)LogonType.NewCredentials,
                  (int)LogonProvider.WinNT50,
                  ref token);
    
        WindowsImpersonationContext context = WindowsIdentity.Impersonate(token);
        CloseHandle(token);
        return context;
    }