Windows impersonation for moving files in C#

When you have a system and you may want to move files in a secure environment without the users having to know the password to the destination machine. The following functions do this by using maintained username, password and domain from the database which can be encrypted and

decrypted. For my case I have used tripledes class to encrypt my parameter values.

 /// </summary> /// source location /// destination location /// domain /// password /// username public static void fnSecureCopy(string Source, string Destination, string Dorm, string Pass, string Usr) { IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUser(Usr, Dorm, clsEncDec.DecryptString(Pass), LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token)) { if (DuplicateToken(token, LOGON32_LOGON_INTERACTIVE, ref tokenDuplicate)) { WindowsIdentity identity = new WindowsIdentity(tokenDuplicate); WindowsImpersonationContext context = identity.Impersonate(); if ((context != null)) { CloseHandle(token); CloseHandle(tokenDuplicate); if (!Directory.Exists(Path.GetDirectoryName(Destination))) Directory.CreateDirectory(Path.GetDirectoryName(Destination)); File.Copy(Source, Destination); clsLogs.fnErrorLog("Impersonated user: " + WindowsIdentity.GetCurrent().Name, "RepoWeb"); context.Undo(); ClsAudit.Log_Audit("Generate", "Generated Format 31" + Destination); } } } if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); } else { //log error clsLogs.fnErrorLog("Failed to impersonate user: " + Dorm + @"\" + Usr, "Impersonation to copy file."); } }

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.