search
Japanese Chinese Nederlands Espanol Italiano Deutsch Francais Twitter Rss Feeds
MicrosoftArticlesForumsFAQs
C# .NET
VB.NET
Visual Studio .NET
ADO.NET
Xml / Xslt
VB 6.0
.NET CF
GDI+
LINQ
Deployment
Security
FoxPro
Silverlight / WPF
Entity Framework
RIA Services

Web ProgrammingArticlesForumsFAQs
JavaScript
ASP
ASP.NET
Web Services

Non-MicrosoftArticlesForumsFAQs
NHibernate
Perl
PHP
Ruby
Java
Linux / Unix
Apple
Open Source

DatabasesArticlesForumsFAQs
SQL Server
Access
Oracle
MySQL
Other Databases

OfficeArticlesForumsFAQs
Excel
Word
Powerpoint
Outlook
Publisher
Money

Operating SystemsArticlesForumsFAQs
Windows 7
Windows Server
Windows Vista
Windows XP
Windows Update
MAC
Linux / UNIX

Server PlatformsArticlesForumsFAQs
BizTalk
Site Server
Exhange Server
IIS

Graphic DesignArticlesForumsFAQs
Macromedia Flash
Adobe PhotoShop
Expression Blend
Expression Design
Expression Web

OtherArticlesForumsFAQs
Subversion / CVS
Ask Dr. Dotnetsky
Active Directory
Networking
Uninstall Virus
Job Openings
Product Reviews
Search Engines
Resumes

 

View Other C# .NET Posts   Ask New Question 
LogonUserA, impersonation
H C posted at Thursday, July 28, 2005 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
Jon Wojtowicz replied at Thursday, July 28, 2005 4: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?
Daniel Schaffer replied at Thursday, July 28, 2005 4: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
Jon Wojtowicz replied at Thursday, July 28, 2005 5: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
H C replied at Thursday, July 28, 2005 5: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
Jon Wojtowicz replied at Thursday, July 28, 2005 6: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>
H C replied at Thursday, July 28, 2005 11:14 PM
.
 
Daniel Schaffer replied at Friday, July 29, 2005 8:34 AM
http://www.eggheadcafe.com/forums/ForumPost.asp?ID=28830&INTID=2
 
Yes, the thanks was to both
H C replied at Friday, July 29, 2005 9: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