C#Active Directory和模拟中远程服务器上的文件系统

时间:2012-01-26 08:27:11

标签: c# filesystems impersonation network-share

这个主题并不新鲜。但我需要一些专业人士的帮助。 我正在制作一个将在本地系统(不是域的计算机)上运行的Windows窗体应用程序。该应用程序将在Active Directory域的共享文件夹上创建文件夹和一些文件。 我读过有关模仿的内容,并试图做出类似这样的事情:Impersonation by using LogonUser

然后我写了下一个代码:

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("Administrator@mydomain.ru", "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);
        }
    }
}

bool结果始终= false 。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我对理解LogonUser功能错了。我在想这个函数获取远程令牌,但它会生成。 这是正确的使用:

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