<p>I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.</p>

[{'answer_id': 48571, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 3, 'selected': True, 'text': '<p>You can use the WindowsIdentity.Impersonate method to \nachieve this. This method allows code to impersonate a different Windows \nuser. Here is a link for more information on this method with a good sample:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx</a></p>\n\n<p>Complete example:</p>\n\n<pre><code>// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.\n// IMPORTANT NOTES:\n// This sample can be run only on Windows XP.  The default Windows 2000 security policy\n// prevents this sample from executing properly, and changing the policy to allow\n// proper execution presents a security risk.\n// This sample requests the user to enter a password on the console screen.\n// Because the console window does not support methods allowing the password to be masked,\n// it will be visible to anyone viewing the screen.\n// The sample is intended to be executed in a .NET Framework 1.1 environment.  To execute\n// this code in a 1.0 environment you will need to use a duplicate token in the call to the\n// WindowsIdentity constructor. See KB article Q319615 for more information.\n\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\nusing System.Security.Permissions;\nusing System.Windows.Forms;\n\n[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]\n[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]\npublic class ImpersonationDemo\n{\n    [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]\n    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,\n        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);\n\n    [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]\n    private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,\n        int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);\n\n    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]\n    public extern static bool CloseHandle(IntPtr handle);\n\n    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]\n    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,\n        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);\n\n    // Test harness.\n    // If you incorporate this code into a DLL, be sure to demand FullTrust.\n    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]\n    public static void Main(string[] args)\n    {\n        IntPtr tokenHandle = new IntPtr(0);\n        IntPtr dupeTokenHandle = new IntPtr(0);\n        try\n        {\n            string userName, domainName;\n            // Get the user token for the specified user, domain, and password using the\n            // unmanaged LogonUser method.\n            // The local machine name can be used for the domain name to impersonate a user on this machine.\n            Console.Write("Enter the name of the domain on which to log on: ");\n            domainName = Console.ReadLine();\n\n            Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);\n            userName = Console.ReadLine();\n\n            Console.Write("Enter the password for {0}: ", userName);\n\n            const int LOGON32_PROVIDER_DEFAULT = 0;\n            //This parameter causes LogonUser to create a primary token.\n            const int LOGON32_LOGON_INTERACTIVE = 2;\n\n            tokenHandle = IntPtr.Zero;\n\n            // Call LogonUser to obtain a handle to an access token.\n            bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),\n                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,\n                ref tokenHandle);\n\n            Console.WriteLine("LogonUser called.");\n\n            if (false == returnValue)\n            {\n                int ret = Marshal.GetLastWin32Error();\n                Console.WriteLine("LogonUser failed with error code : {0}", ret);\n                throw new System.ComponentModel.Win32Exception(ret);\n            }\n\n            Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No"));\n            Console.WriteLine("Value of Windows NT token: " + tokenHandle);\n\n            // Check the identity.\n            Console.WriteLine("Before impersonation: "\n                + WindowsIdentity.GetCurrent().Name);\n            // Use the token handle returned by LogonUser.\n            WindowsIdentity newId = new WindowsIdentity(tokenHandle);\n            WindowsImpersonationContext impersonatedUser = newId.Impersonate();\n\n            // Check the identity.\n            Console.WriteLine("After impersonation: "\n                + WindowsIdentity.GetCurrent().Name);\n\n            // Stop impersonating the user.\n            impersonatedUser.Undo();\n\n            // Check the identity.\n            Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);\n\n            // Free the tokens.\n            if (tokenHandle != IntPtr.Zero)\n                CloseHandle(tokenHandle);\n\n        }\n        catch(Exception ex)\n        {\n            Console.WriteLine("Exception occurred. " + ex.Message);\n        }\n\n    }\n}\n</code></pre>\n'}, {'answer_id': 48606, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 2, 'selected': False, 'text': '<p>Impersonate will change the Thread context. If you want to change the identity and launch a separate process, you will have to use runas command.</p>\n\n<p>The .NET Developer\'s Guide to Windows Security by Keith Brown is an excellent read which describes all the security scenarios.\n<a href="http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook.HomePage" rel="nofollow noreferrer">Online version</a> is also available.</p>\n'}]
['https://Stackoverflow.com/questions/48567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1360/']