Impersonation for file copy across network

可紊 提交于 2020-01-24 11:07:10

问题


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);
}


来源:https://stackoverflow.com/questions/8149648/impersonation-for-file-copy-across-network

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!