Impersonating by username and password

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

       

Sometimes it is required to authenticate the user when username and password are known. For this the windows API LogonUser function is used. This function, with little bit .NET code, can be used to fully authenticate the thread in .NET as it would be started by that interactive user.

Following code shows how to do that:

      

        [DllImport("advapi32.dll")]

        protected static extern bool 
        LogonUser(String lpszUsername, 
                  String lpszDomain,
                  String lpszPassword,

                  int dwLogonType,
                  int dwLogonProvider,
                  out int phToken);

        

        public static void Authenticate(string userName,
                                        string password)

        {

            int token;

 

            bool loggedOn = LogonUser(userName,
            null, password,
            2/*2 is if local user is logged on.*/,
            0, out token);

 

            if (!loggedOn)

            {

                 throw new SecurityException("...");

            }

            else

            {

               IntPtr token2 = new IntPtr(token);

               WindowsIdentity mWI = new WindowsIdentity(token2);

               WindowsImpersonationContext mwic = mWI.Impersonate();

    

               // Test

               WindowsIdentity mWI1 = WindowsIdentity.GetCurrent();

            }

        }

 

More about impersonation can be found here.


Posted Oct 19 2007, 11:50 PM by Damir Dobric
Filed under: , ,

Comments

dominick wrote re: Impersonating by username and password
on 10-22-2007 16:09

You are missing crucial cleanup code

a) you have to call Win32 CloseHandle on the handle returned by LogonUser

b) you don't have to duplicate the token - this is done by the WindowsIdentity ctor

c) put the WindowsIdentity in a using statement to enforce prompt handle cleanup

d) put the WindowsImpersonationContext into a using statement to ensure that impersonation gets undone.

dominick

Damir Dobric Posts wrote UserImpersonation in WindowsForms and WPF
on 03-19-2010 10:48

Following example shows how to enforce interactive user in Windows Forms or WPF applications to become

DamirDobric wrote User Impersonation in WindowsForms and WPF
on 03-19-2010 11:05

Following example shows how to enforce interactive user in Windows Forms or WPF applications to become

developers.de is a .Net Community Blog powered by daenet GmbH.