Impersonation for file copy across network

2019-05-14 12:49发布

问题:

I want to copy a file from remote machine in the same domain. so I am using impersonation to do that.

I am using DLLImport of advapi32.dll and it properly impersonate the user.

Now when below code line executed i got the following error.

\\line

File.Copy(@"\\sins00048178\D$\BNCustody\Swift\Received_from_SWIFT\Error_files\E03248681_error.out", @"C:\E03248681_error.out", true);


\\Error
"Logon failure: user not allowed to log on to this computer."

COMPLETE CODE AS REQUESTED

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

IntPtr userHandle = IntPtr.Zero;
bool loggedOn = LogonUser(userid, domain, pass, 9, 0, out userHandle);

 if (loggedOn)
 {
    WindowsImpersonationContext context = WindowsIdentity.Impersonate(userHandle);
           File.Copy(@"\\sins00048178\D$\BNCustody\Swift\Received_from_SWIFT\Error_files\E03248681_error.out", @"C:\E03248681_error.out", true);

    context.Undo();

 }

Thanks in advance....

回答1:

The code that I have that does impersonation is similar, but there are small differences from yours. This was passed down from other developers at my group and I'm sure it's copy/paste from somewhere online. It does work though, and we use it in windows services and forms.

//defined elsewhere
WindowsImpersonationContext impersonatedUser;
WindowsIdentity newId;
IntPtr tokenHandle;

//Impersonate
tokenHandle = IntPtr.Zero;
bool returnValue = LogonUser(userName, domainName, password, 2, 0, ref tokenHandle);
if (returnValue) {
    newId = new WindowsIdentity(tokenHandle);
    impersonatedUser = newId.Impersonate();
} else {
    //do some error handling
}

//Undo impersonation
if (impersonatedUser != null) {
    impersonatedUser.Undo();
}
if (tokenHandle != IntPtr.Zero) {
    CloseHandle(tokenHandle);
}