Thursday, January 5, 2012

Run application c# with another username

using System;
using System.Web;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.IO;
using System.Configuration;

///
/// FileAccess
public class FileAccessUtility
{

#region Constructor
public FileAccessUtility()
{
}
#endregion
#region Const
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
#endregion
#region DllImport
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

#endregion


#region Methods




public void Copy(string Source, string Destionation)
{
string user, pass, domain;
user = ""; //ConfigurationManager.AppSettings["UserFileAccess"].ToString();
pass = ""; //ConfigurationManager.AppSettings["PassUserFileAccess"].ToString();
domain = ""; //ConfigurationManager.AppSettings["DomainUserFileAccess"].ToString();

if (impersonateValidUser(user, domain, pass))
{
File.Copy(Source, Destionation);
undoImpersonation();
}
else
{
throw new Exception("Autentificarea a esuat pentru userul: " + domain + "\\" + user);
}
}

public void WriteToFile(string filePath, ref byte[] Buffer)
{
string user = "", pass = "", domain = "";
//user = ConfigurationManager.AppSettings["UserFileAccess"].ToString();
//pass = ConfigurationManager.AppSettings["PassUserFileAccess"].ToString();
//domain = ConfigurationManager.AppSettings["DomainUserFileAccess"].ToString();

if (impersonateValidUser(user, domain, pass))
{
WriteFile(filePath, ref Buffer);
undoImpersonation();
}
else
{
throw new Exception("Autentificarea a esuat pentru userul: " + domain + "\\" + user);
}
}

public byte[] ReadFromFile(string filePath)
{
string user = "", pass = "", domain = "";
byte[] buffer;

//user = ConfigurationManager.AppSettings["UserFileAccess"].ToString();
//pass = ConfigurationManager.AppSettings["PassUserFileAccess"].ToString();
//domain = ConfigurationManager.AppSettings["DomainUserFileAccess"].ToString();

if (impersonateValidUser(user, domain, pass))
{
buffer = ReadFile(filePath);
undoImpersonation();
return buffer;
}
else
{
throw new Exception("Autentificarea a esuat pentru userul: " + domain + "\\" + user);
}
}

private void WriteFile(string filePath, ref byte[] Buffer)
{
if (!Directory.Exists(Path.GetDirectoryName(filePath)))
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
FileStream newFile = new FileStream(filePath, FileMode.CreateNew);
newFile.Write(Buffer, 0, Buffer.Length);
newFile.Close();
}

private byte[] ReadFile(string filePath)
{
byte[] buffer;
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read

// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading


fileStream.Close();
return buffer;


}

private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

private void undoImpersonation()
{
impersonationContext.Undo();
}




#endregion
}





Call the class

FileAccessUtility fileAcces;
byte[] myData;
HttpPostedFile myFile;
if (fileUploadDocumentSolicitant.PostedFile.InputStream.Length < 7000000)
{
Random rnd = new Random();
fileAcces = new FileAccessUtility();
}

No comments:

Post a Comment