C# File system on remote server in ActiveDirectory and Impersonation

1.2k Views Asked by At

This theme are not new. But I need help of some professional. I am making a windows form application which will run on local system(not domain's computer). The application would creating folder and some files on Active Directory domain's shared folder. I have read about Impersonation and have tried to make some thing like this: Impersonation by using LogonUser

Then I wrote the next code:

using System.Security.Principal;
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
    private enum LogonSessionType : uint
    {
        Interactive = 2,
        Network,
        Batch,
        Service,
        NetworkCleartext = 8,
        NewCredentials
    }

    private enum LogonProvider : uint
    {
        Default = 0,
        WinNT35,
        WinNT40,
        WinNT50
    }
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool CloseHandle(IntPtr handle);
    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool LogonUser(
        string principal,
        string authority,
        string password,
        LogonSessionType logonType,
        LogonProvider logonProvider,
        out IntPtr token);

    public Form1()
    {
        InitializeComponent();
    }

    protected void btnConnect_Click(object sender, EventArgs e)
    {
        IntPtr token = IntPtr.Zero;
        WindowsImpersonationContext impersonateUser = null;
        try
        {
            bool result = LogonUser("[email protected]", "192.168.1.1", "SomeP@ssWorD",
                                    LogonSessionType.Network, LogonProvider.Default, out token);
            if(result)
            {
                WindowsIdentity id = new WindowsIdentity(token);
                impersonateUser = id.Impersonate();
                string showtext = string.Format("Identity: {0}", WindowsIdentity.GetCurrent().Name);
                MessageBox.Show(showtext);
            }
            else
            {
                string showtext = string.Format("Identity: {0}", "Fail");
                MessageBox.Show(showtext);
            }
        }
        catch
        {
        }
        finally
        {
            if(impersonateUser!=null)
                impersonateUser.Undo();
            if (token != IntPtr.Zero)
                CloseHandle(token);
        }
    }
}

But bool result is always = false. What am I doing wrong?

1

There are 1 best solutions below

0
On

i was wrong about understanding of LogonUser function. I was thinking that this function get remote token, but it generate. Here is the right using:

bool result = LogonUser("Administrator", "mydomain.ru", "SomePa$$worD", LogonSessionType.NewCredentials, LogonProvider.Default, out safeTokenHandle);