Copy files over the network (authentication required)

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

net use not an option, and I cannot get LogonUser to work.

Any ideas?


[Change] Here is the 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 complete the File.Copy operation in using(new UserImpersonator(username, password)) , I get:

System.IO.IOException: Login failed: Unknown username or invalid password.

If, however, I first try to connect to a shared resource in Explorer (by entering authentication information when it requests it), File.Copy works. It seems that the above code does nothing.

+7
authentication c # file io
source share
3 answers

You can use WNetUseConnection with p / invokes.

See this topic:

Access to a shared file (UNC) from a remote, untrusted domain with credentials

+4
source share

Can I direct you to my answer, which I put on here ? It should work for your needs.

+1
source share

You really need to log in to the local account, which is a member of the group on the domain controller, or just log in directly to the DC account. However, without additional information, I am not sure what you are facing. Could you send the code?

change

Ok, I see two problems.

The main problem is that you are passing an empty string for the LogonUser domain parameter. Try passing the name of the local computer or network DC.

A side issue is that you need to log in using a batch or interactive, rather than a network. Logging on to the network gives you the impersonation token, not the main logon, which may prevent you from reaching network resources if delegation is not enabled.

In addition, as soon as you do this, you will want to completely remove IntPtr and replace it with SafeHandle.

0
source share

All Articles