C# .NET - LogonUserA, impersonation

Asked By H C
28-Jul-05 12:49 PM
Ok, I am trying to authenticate a user by Domain, then check to see if the user is in my custom database. All I want to do here is check to see if the user exists on the domain, and then the application database handles everything else about the user...Please help. Thanks

The below code is right from here
http://support.microsoft.com/?scid=306158

If I create a local machine user, and specify the machine name here, I am able to login.
<add key="Domain" value="Machine_Name" />

But, if I specify the Domain name (which is really what I need to do), I always get Login Failed
<add key="Domain" value="DOMAIN_Name" />


        private void _btnLogin_Click(object sender, System.EventArgs e)
        {
            WinFormAuth wa = new WinFormAuth();
            string _domain = System.Configuration.ConfigurationSettings.AppSettings["Domain"];
            //Do DB Lookup
            try
            {
                if(wa.impersonateValidUser(_userName.Text, _domain, _password.Text))
                {
                    //Insert your code that runs under the security context of a specific user here.
                    
                    wa.undoImpersonation();
                    
                    if(Request.QueryString["url"]==null)
                        Response.Redirect("dashboard_summary.aspx");
                    else
                        Response.Redirect(Request.QueryString["url"]);
                }
                else
                {
                    //Your impersonation failed. Therefore, include a fail-safe mechanism here.
                        _lblMessage.Text="Login Failed";
                }
            }
            catch(Exception ex)
            {
                _lblMessage.Text=ex.Message;
            }
        }



    public class WinFormAuth
    {
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        WindowsImpersonationContext impersonationContext;

        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
        public static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
        public static extern  bool CloseHandle(IntPtr handle);

        public bool impersonateValidUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if(RevertToSelf())
            {
                if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if(DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if(token!= IntPtr.Zero)
                CloseHandle(token);
            if(tokenDuplicate!=IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }

        public void undoImpersonation()
        {
            impersonationContext.Undo();
        }
    }

This code fails on  This code fails on

28-Jul-05 04:45 PM
Windows 2000 for security issues. It should work fine on Windows XP or 2003.

If you are using Active Directory you might want to consider changing the code to use the System.DirectoryServices.DirectoryEntry classes to see if the user exists in the domain.

Here's a link that shows you how to validate a user exisit using Active Directory
http://www.c-sharpcorner.com/Code/2005/June/ADand.NET.asp

Windows Authentication?  Windows Authentication?

28-Jul-05 04:53 PM
If you use Windows Authentication, they won't be able to get on to the site if they aren't already authenticated on the domain. Then you can use Request.ServerVariables to grab their authentication info.

It appears he's trying to  It appears he's trying to

28-Jul-05 05:03 PM
forms authentication. Windows authentication won't work through most firewalls, it's typically blocked for security reasons. Most palces use Basic over HTTPS which would authenticate the user after they login.

I'm not sure what his specific requirements are so I only answered the question asked.

BTW, I'm not the one who posted the question.
This is one Windows NT 4  This is one Windows NT 4
28-Jul-05 05:22 PM
It does work fine on Windows XP and 2003. Thats what was bugging me out.

This is an INTRAnet only app. What needs to happen is that the user need to go to
http://machinename/website/default.aspx

on this page, I want them to type in their domain username and password. Authenticate throught the domain, and then the app handles the rest. Any thoughts on how to get this to work? Thanks so much both of your for the replies. 

HC
You can use windows integrated  You can use windows integrated
28-Jul-05 06:14 PM
authentication on the website and the user would not have to input any information. It would use their username from when they logged into their machine. Since this is an intranet app there wouldn't be the security risk of going over the internet.

That code definitely does not work on NT4.
That works great  Thanks<eop>  That works great Thanks<eop>
28-Jul-05 11:14 PM
.
 
29-Jul-05 08:34 AM
http://www.eggheadcafe.com/forums/ForumPost.asp?ID=28830&INTID=2
Yes, the thanks was to both  Yes, the thanks was to both
29-Jul-05 09:46 AM
I know that you responmded with the same answer. I was hoping to make it works with FORMS authentication, but this way will definately do. Again, thank you
Create New Account
help
Cannot Update my computer Windows 7 When I try to update my computer it takes me to this screen but then just stops, No active X control bar comes up anything. . . Anyone have a solution??? Checking if your computer has the latest version of Windows updating software for use with the website… The website uses ActiveX controls to determine which the control is digitally signed by Microsoft before installing it or allowing it to run. Windows Update Discussions DWNBsGEoMUUCk9DeQ3dZC7nwVyI (1) Rtjs1o1SsJInOKKDHvmBaEFRz8k (1) PZPodjs5Sb0rBgjGMrywFST1kSI (1) G2zcZZiahNu6vu6DZhU0ZHNsc4E (1) DuZMGhCD3sFKFlpQ4S5vJ (1) NeZ5vHvF3yYt4NVlFydRfGCvo (1) LL7ccQ7tTEJQUJDkIs (1) ISOGBsX9WpxVM (1) The version of Windows is _ __ __ __ . The Antivirus / security software installed is _ __ __ __ _ . Either a 3rd party firewall, a the installation of the ActiveX control needed to obtain updates. Do a manual visit to Windows | Microsoft Update When you get that error message, close the browser Then go to Start Forgotten = = = = = = = = = = = = = = = 2010-05-07 13:58:39:189 1300 11f4 Agent * Title = Security Update for Windows Vista (KB980232) 2010-05-07 13:58:39:189 1300 11f4 Agent * UpdateId = {0F6F26DC-954A 105 2010-05-07 13:58:39:189 1300 11f4 Agent * Title = Security Update for Windows Vista (KB975467) 2010-05-07 13:58:39:189 1300 11f4 Agent * UpdateId = {DA896AE2-83F3
Same problem Windows Installer 3.1 v2 will not install. Windows 7 I use Windows Automatic Update to install my updates. Just recently, it shows to update to Windows Installer 3.1 Redistributable (v2). I have it update but it says that it could DoInstallation: FetchSourceURL for c: \ bf69b2f4cb1ad887fac3a65d6255e4c0 \ update \ update_wxp.inf failed 2.203: CreateUninstall = 1, Directory = C: \ WINDOWS \ $MSI31Uninstall_KB893803v2$ 2.203: LoadFileQueues: UpdSpGetSourceFileLocation for halaacpi.dll failed: 0xe0000102 2.219: BuildCabinetManifest: update.url absent 2.234: Starting AnalyzeComponents 2.234: AnalyzePhaseZero used 0 ticks 2.234: No c: \ windows \ INF \ updtblk.inf file. 2.234: SetupFindFirstLine in LoadExclusionList Failed with error: 0xe0000102 2.234 successfully complete this installation, the following services will automatically be stopped and restarted. 21.781: Windows Installer. 24.906: LoadFileQueues: UpdSpGetSourceFileLocation for halaacpi.dll failed: 0xe0000102 25.719: Num Ticks for halaacpi.dll failed: 0xe0000102 47.031: System Restore Point set. 47.094: Copied file: C: \ WINDOWS \ system32 \ spmsg.dll 47.469: PFE2: Not avoiding Per File Exceptions. 47.484: GetCatVersion: Failed
Missing Windows update reported as a vulnerability by TMH and Bela Windows 7 Hello. Trend Micro Housecall reported as a vulnerability in my system the missing update components', the one that corresponds to my OS is 'Microsoft JScript 5.6 on Microsoft Windows XP Service Pack 1 and Microsoft Windows XP Service Pack 2'. In Windows Control Panel> Add and Remove programs. I also downloaded and installed the utility 'Belarc Advisor X KB917344 on 06-08-2007 (details. . .) Reinstall!» I searched through all of my Windows updates installed and didn't found KB917344. I also went to Microsoft Update Website and
Why do you still use Windows XP? Windows 7 Give your reasons. Do you plan to upgrade ever? If so, when and why? If you use both XP and 7, do you ever plan on ditching XP for good? What will you do when support is dropped to the point where this OS will be problematic with new hardware? Personally I am waiting for Windows 8 to release a second service pack. XP sucked when it first came out until SP1. Even then, I find the moron-babysitting did not work, it had to enabled then disabled to be disabled for real. Sigh. . . Windows XP Discussions Windows XP (1) Windows Embedded (1) Windows Server (1) Microsoft Word (1) Windows
Bootable CD problem Windows 7 I have two problems 1 / format 650MB primary partition with FAT32, set active using dispart in WinPE2. After I fill this partition with pre-FBA image, it does I am using Feature Pack 2007, my sytem is a tablet with one HD Thanks, Windows XP Embedded Discussions PM (1) WINDOWS (1) System (1) CallEntryPointThread (1) DllRegisterServer (1) CD (1) FBAAddDevInstanceId (1) FBA (1) What documentation the support for USB CD-ROMs. Regards, Sean Liming www.sjjmicro.com / www.seanliming.com XP Embedded Book Author - XP Embedded Advanced, XP Embedded Supplemental Toolkit PF2007 help file. This link shows a success of XPe CD for