logo

LogonUserA, impersonation

H C replied

Thursday, July 28, 2005 12:49:45 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();
        }
    }

Biography
H has not submitted biographical details.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

This code fails on

Jon Wojtowicz replied

EggHeadCafe's human moderators scored this post for our messageboard contest.

Thursday, July 28, 2005 4:45:16 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

Biography
I'm currently with a large insurance company in enterprise software engineering. I'm currently developing enterprise wide components and services. I'm also an MCT and conduct internal training on C#, ASP.Net, Web Services, and Windows programming in .Net, assist with architecture, coordinate and present at internal monthly forums. I'm an MCSD and MCDBA as well. I was recently awarded a C# MVP. In my free time I like to garden and work around the house.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

Windows Authentication?

Daniel Schaffer replied

EggHeadCafe's human moderators scored this post for our messageboard contest.

Thursday, July 28, 2005 4:53:21 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.

Biography
Daniel has not submitted biographical details.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

It appears he's trying to

Jon Wojtowicz replied

EggHeadCafe's human moderators scored this post for our messageboard contest.

Thursday, July 28, 2005 5:03:41 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.

Biography
I'm currently with a large insurance company in enterprise software engineering. I'm currently developing enterprise wide components and services. I'm also an MCT and conduct internal training on C#, ASP.Net, Web Services, and Windows programming in .Net, assist with architecture, coordinate and present at internal monthly forums. I'm an MCSD and MCDBA as well. I was recently awarded a C# MVP. In my free time I like to garden and work around the house.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

This is one Windows NT 4

H C replied

Thursday, July 28, 2005 5:22:34 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

Biography
H has not submitted biographical details.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

You can use windows integrated

Jon Wojtowicz replied

EggHeadCafe's human moderators scored this post for our messageboard contest.

Thursday, July 28, 2005 6:14:37 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.

Biography
I'm currently with a large insurance company in enterprise software engineering. I'm currently developing enterprise wide components and services. I'm also an MCT and conduct internal training on C#, ASP.Net, Web Services, and Windows programming in .Net, assist with architecture, coordinate and present at internal monthly forums. I'm an MCSD and MCDBA as well. I was recently awarded a C# MVP. In my free time I like to garden and work around the house.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

That works great Thanks<eop>

H C replied

Thursday, July 28, 2005 11:14:29 PM

.

Biography
H has not submitted biographical details.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

Daniel Schaffer replied

Friday, July 29, 2005 8:34:12 AM

http://www.eggheadcafe.com/forums/ForumPost.asp?ID=28830&INTID=2

Biography
Daniel has not submitted biographical details.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor

Yes, the thanks was to both

H C replied

Friday, July 29, 2005 9:46:39 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

Biography
H has not submitted biographical details.

Site Rank:  Not applicable - Current Winnings:  $0.00

Reply Reply Using Power Editor
 

Didn't Find The Answer You Were Looking For?

EggHeadCafe has experts online right now that may know the answer to your question.  We pay them a bonus for answering as many questions as they can.  So, why not help them and yourself by becoming a member (free) and ask them your question right now?
Ask Question In Live Forum








  $1000    Adam Houldsworth - $182  |  Jonathan VH - $157  |  Kirtan Patel - $125  |  F Cali - $98  |  Mr. Khan - $92  |  more Neado  |  Free Icons  |  Privacy  |   (c) 2010