How to use Impersonation for specific user using C#

See the below 4 simple steps to impersonate the code under specific user.

Step1. Include the below namespaces in the class.

using System.Runtime.InteropServices;

using System.Security.Principal;

Step 2. Include two API functions and two enum in the class as below.

#region << Windows Api>>

[DllImport(“advapi32.dll”, SetLastError = true)]

static extern bool LogonUser(

string principal,

string authority,

string password,

LogonSessionType logonType,

LogonProvider logonProvider,

out IntPtr token);

[DllImport(“kernel32.dll”, SetLastError = true)]

static extern bool CloseHandle(IntPtr handle);

#endregion

#region << public Enum >>

enum LogonSessionType : uint

{

Interactive = 2,

Network,

Batch,

Service,

NetworkCleartext = 8,

NewCredentials

}

enum LogonProvider : uint

{

Default = 0, // default for platform (use this!)

WinNT35,     // sends smoke signals to authority

WinNT40,     // uses NTLM

WinNT50      // negotiates Kerb or NTLM

}

#endregion

Step 3. Go to the function where you want to impersonate your Code and include the below code..

IntPtr token = IntPtr.Zero;

WindowsImpersonationContext impersonatedUser = null;

string adminAccount=”administrator”;

string adminPassword=”pwd”;

string domainName=”IND”;

try

{

//impersonate function

bool result = LogonUser(adminAccount, domainName, adminPassword, LogonSessionType.Network, LogonProvider.Default, out token);

if (result)

{

WindowsIdentity id = new WindowsIdentity(token);

impersonatedUser = id.Impersonate();

//**************

//Write your code that you want to impersonate;

//————–

}

}

catch (Exception ex)

{

}

finally

{

// Stop impersonation and revert to the process identity

if (impersonatedUser != null) impersonatedUser.Undo();

// Free the token

if (token != IntPtr.Zero)  CloseHandle(token);

}

Step 4.

Enjoy coding.

Advertisements

One thought on “How to use Impersonation for specific user using C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s