Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying files over network (requiring authentication)

Is there some way to authenticate as a local (not network) user in order to copy files over the network in .Net?

net use is not an option, and I can't seem to get LogonUser to work.

Any ideas?


[Edit] Here is some code:

public class UserImpersonator : IDisposable
{
    private WindowsImpersonationContext _impersonationContext;
    private IntPtr _userHandle = IntPtr.Zero;

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

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hHandle);

    public UserImpersonator(string username, string password)
    {
        LogonUser(username, "", password, (int)LogonType.LOGON32_LOGON_NETWORK,
                  (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out _userHandle);
        _impersonationContext = WindowsIdentity.Impersonate(_userHandle);
    }

    public void Dispose()
    {
        CloseHandle(_userHandle);
        _impersonationContext.Undo();
    }

    private enum LogonType : int
    {
        LOGON32_LOGON_INTERACTIVE = 2,
        LOGON32_LOGON_NETWORK = 3,
        LOGON32_LOGON_BATCH = 4,
        LOGON32_LOGON_SERVICE = 5,
        LOGON32_LOGON_UNLOCK = 7,
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
        LOGON32_LOGON_NEW_CREDENTIALS = 9,
    }

    private enum LogonProvider
    {
        LOGON32_PROVIDER_DEFAULT = 0,
    }
}

When I wrap the File.Copy operation in using(new UserImpersonator(username, password)), I get:

System.IO.IOException: Logon failure: unknown user name or bad password.

If, however, I first try to connect to the share in explorer (entering the authentication info when it asks for it), the File.Copy works. It appears that the above code doesn't do anything at all.

like image 639
BlueRaja - Danny Pflughoeft Avatar asked Apr 26 '10 17:04

BlueRaja - Danny Pflughoeft


2 Answers

You can use WNetUseConnection with p/invokes.

See this thread:

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

like image 50
Joe Avatar answered Oct 16 '22 08:10

Joe


Might I direct you to my answer I put over here? It should work for your needs.

like image 1
Jesse C. Slicer Avatar answered Oct 16 '22 10:10

Jesse C. Slicer