Here's what you need:
using System;
using System.Security .Principal;
using System.Security .Permissions;
using System.Runtime. InteropServices ;
using System.Threadin g;
namespace Impersonate
{
/// <summary>
/// Summary description for ImpersonateUser .
/// </summary>
public class ImpersonateUser
{
[DllImport("adva pi32.dll", SetLastError=tr ue)]
private static extern bool LogonUser(strin g lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider ,
ref IntPtr phToken);
[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
private static extern bool CloseHandle(Int Ptr handle);
// constants used by LogonUser() method
private const int LOGON32_LOGON_N ETWORK = 3;
private const int LOGON32_PROVIDE R_DEFAULT = 0;
private WindowsImperson ationContext wic = null;
private WindowsIdentity currentIdentity = null;
public ImpersonateUser (string login, string password, string domain)
{
// Get current Identity
currentIdentity = WindowsIdentity .GetCurrent();
// handle returned from the LogonUser() method
IntPtr handle = new IntPtr(0);
handle = IntPtr.Zero;
// try to login to the domain
bool logonUser = LogonUser(login , domain, password,
LOGON32_LOGON_N ETWORK, LOGON32_PROVIDE R_DEFAULT, ref handle);
// login unsuccessful
if(!logonUser)
{
// get the error
int lastWin32Error = Marshal.GetLast Win32Error();
throw new Exception("Impe rsonateUser failed<br>Win32 Error: " +
lastWin32Error) ;
}
// create a new WindowsIdentity , set the CurrentPrincipa l and Impersonate
the user
WindowsIdentity wi
= new WindowsIdentity (handle, "NTLM", WindowsAccountT ype.Normal, true);
Thread.CurrentP rincipal = new WindowsPrincipa l(wi);
wic = wi.Impersonate( );
// close the handle
CloseHandle(han dle);
}
public void Undo()
{
// Impersonate back to original identity
wic.Undo();
Thread.CurrentP rincipal = new WindowsPrincipa l(currentIdenti ty);
currentIdentity .Impersonate();
}
}
}
"Jim Heavey" wrote:
My goal is to upload/download files to a shared folder. I have been granted
a "generic" account to be used for this purpose. I have designed a page
which will do this download. My quandry is when the user access the page, I
retrieve their "User.Ident ity" and log activity to that user on this screen
to the Database. If I used impersonation in web config file, then I really
loose the true user's identify and can not really log there usage into the
system because the "generic" id is substituted.
I have been reading that I can use Impersonation via code for a portion of
the page. This looks like a solution to my problem but I seem to be limited
to the account that is actually using the application. Is there a way for me
to create a WindowsIdentity object with my generic account? Do you have an
example?