Welcome to MSDN Blogs Sign in | Join | Help
WindowsIdentity Impersonation using C# Code

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security.Permissions;

namespace Test
{
    public class ImpersonateUser
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(
        String lpszUsername,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);
        private static IntPtr tokenHandle = new IntPtr(0);
        private static WindowsImpersonationContext impersonatedUser;
        // If you incorporate this code into a DLL, be sure to demand that it
        // runs with FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        public void Impersonate(string domainName, string userName, string password)
        {
            //try
            {
                // Use the unmanaged LogonUser function to get the user token for
                // the specified user, domain, and password.
                const int LOGON32_PROVIDER_DEFAULT = 0;
                // Passing this parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_INTERACTIVE = 2;
                tokenHandle = IntPtr.Zero;
                // ---- Step - 1
                // Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser(
                userName,
                domainName,
                password,
                LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle); // tokenHandle - new security token
                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();                   
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                // ---- Step - 2
                WindowsIdentity newId = new WindowsIdentity(tokenHandle);
                // ---- Step - 3
                impersonatedUser = newId.Impersonate();
            }
        }
        // Stops impersonation
        public void Undo()
        {
            impersonatedUser.Undo();
            // Free the tokens.
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);
        }
    }
}

how to use it

             ImpersonateUser iu = new ImpersonateUser();
            iu.Impersonate("domain", "userName", "password");
            //your code
            iu.Undo();

Posted: Thursday, May 29, 2008 4:18 AM by itsmeskv

Comments

mettlus shaw said:

works! though how can I accomplish same thing via web.config on IIS7?

Thanks

# February 3, 2009 4:48 PM

Dylan Baxter said:

A very useful addition to my class library! Thank you!

# February 11, 2009 4:19 PM

Agha Usman said:

FileStream data type is a very important feature of SQL Server 2008 and gradually getting popular amongst

# March 15, 2009 4:08 PM

hassan said:

When program was performing,The error is shown:

Logon failure: unknown user name or bad password.

please help me

# April 19, 2009 6:35 PM

Ron Laughton said:

In answer to Mettlus:

web.config

<configuration>

  <system.web>

   <identity impersonate="true" userName="DOMAIN\USERNAME" password="PASSWORD" />

  </system.web>

</configuration>

However, it may not be wise to let every session have impersonation.

# June 2, 2009 2:33 PM

David said:

I've been looking for some time for code that will allow me to perform an identity impersonate within a HttpModule and this code did exactly what I needed. Thanks.

# June 29, 2009 11:08 AM

Adeel said:

Please giuide me the domain name is the Server Machine name or Remote Machine name?

# June 30, 2009 5:35 AM

Marten vanZwietering said:

I rarely post in these things but I just wanted to let you know I really liked this code - and it did exactly what I needed.

# September 30, 2009 10:33 AM

Usman said:

Great Code; Works Perfectly. Thank you for that

# October 28, 2009 1:22 PM

Dodge said:

Excellent code, helped me a lot

# November 3, 2009 10:22 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker