Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Active Directory C# » Authenticate a user against the Active Directory

Authenticate a user against the Active Directory

This article serves as a guide to using System.DirectoryServices (SDS) ADSI to access user and group in the Windows Active Directory. Authenticate a user against the Active Directory using the user ID and password.

Page Views : 133871
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


This article serves as a guide to using System.DirectoryServices (SDS) ADSI to access user and group in the Windows Active Directory. Authenticate a user against the Active Directory using the user ID and password.

LDAP, ADSI and SDS

Lightweight Directory Access Protocol (LDAP) is an industry standard directory access protocol (basically set of protocols) for accessing information directories. In Windows, LDAP is the primary way the Operating System accesses the Active Directory database. Active Directory is the information hub of the Windows Server operating system and index all the data in their entries, and "filters" may be used to select just the person or group you want, and return just the information you want. Active Directory enables centralized, secure management of an entire network and promises to support a single unified view of all objects (such as user accounts, groups, computers and sites) on a network and locating and managing resources faster and easier.

Active Directory Service Interfaces (ADSI) is a COM-based programmatic interface for Microsoft Windows Active Directory that allows you to create custom scripts to administer Active Directory. ADSI-enabled scripts are capable of performing a wide range of administrative tasks involving Active Directory. Active Directory administration involves managing the life cycle of directory objects from initial creation, modification, searching to deletion.

In the .NET Framework, System.DirectoryServices (SDS) is a namespace that provides simple programming access to LDAP directories such as Active Directory from managed code. System.DirectoryServices is built on the Active Directory Service Interfaces (ADSI) API.

User's login using SDS (ADSI) and Database

Authenticate a user against the Active Directory using the user ID and password. When a user wants to login to your software, he can login using network user/pass provided to him by network administrator. You need not implement and maintain the custom implementation for user/pass using database table. You can simply check for windows users using SDS (ADSI) and validate the entered user/pass against the windows domain. You can even set the permission that user should also belong to particular group in order to access the software.

In the example shown here both types of login are used, one using the simple database table to maintain username/password and second, using Windows domain user by SDS ADSI.

ADSI.gif

Login Using Active Directory Services (SDS)

In order to use SDS, first we have to set properties of LDAP server. Here database ADSI_PARAMETER table is used to set the LDAP properties.

CREATE TABLE [dbo].[ADSI_PARAMETER] (
 [ParameterName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [ParameterValue] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

Enter following data to table in ParameterName and ParameterValue fields

Parameter Name ParameterValue
ServerName WindowsDomainServer
BaseDN DC=DomainName,DC=COM
UserDN OU=Users
GroupName CN=Operater, OU=Groups
AccountFilter sAMAccountName

Where ServerName is your domain server machine name. BaseDN is your domain name, most of the time it is company name. UserDN is organizational unit where user should exist. GroupName is organizational unit, to which user should belong in order to access your software. AccountFilter is filter for account name; mostly it is sAMAccountName in windows.

Now we have set the parameter for LDAP server, when the user submit the user/pass from login dialog box with ADSI option. We will pick up the LDAP parameters from database and search the data against parameters and user/pass.

Code for submit button click event. Declare a form level variable int i=0.

private void btnSubmit_Click(object sender, System.EventArgs e)

{

          if(txtUserName.Text.Trim().Equals("") || txtPassword.Text.Trim().Equals(""))

          {

                   MessageBox.Show("Please Enter UserName/Password...");

                   txtPassword.Text="";

                   txtUserName.Text="";

          }

          else

          {

                   //if ADSI radio box is selected call ADSI Login else call simple database login

                   if(rdoADSI.Checked==true)

                   {

                             GetADSILogin();

                   }

                   else

                   {

                             GetDatabaseLogin();

                   }

          }

}

Code for GetADSILogin function. You need to set reference to System.DirectoryService through add reference dialog box in order to use SDS.

public void GetADSILogin()

{

          try

          {

                   string strServerName = "";

                   string strBaseDN = "" ;      

                   string strUserDN = "";

                   string strGroupName = "";

                   string strAccountFilter = "";

                   //Port no for LDAP Default is 389

                   string strPortNo = "389";

                   Boolean blnGroupUser=false;

                   //Data source string

                   string source = "Data Source=ATHAKUR;Initial Catalog=Times;user=sa;password=sa" ;

                   //SQL statement that will be issued

                   string select = "SELECT * from ADSI_PARAMETER";

                   //SQL Connection

                   SqlConnection conn=new SqlConnection(source);

                   // Open the database connection

                   conn.Open () ;

                   // Create the SQL command...

                   SqlCommand cmd = new SqlCommand ( select , conn ) ;

                   //Execute Data reader

                   SqlDataReader myReader = cmd.ExecuteReader();

                   //Check if any rows return against user/pass

                   if(myReader.HasRows)

                   {

                             while(myReader.Read())

                             {

                                      //Store the parameter's data in variables

                                      string strParameterName = myReader.GetString(0).Trim();

                                      string strParameterValue = myReader.GetString(1).Trim();

 

if(strParameterName.ToUpper().Equals("SERVERNAME"))

strServerName=strParameterValue; 

if(strParameterName.ToUpper().Equals("BASEDN"))

strBaseDN=strParameterValue;

if(strParameterName.ToUpper().Equals("USERDN"))

strUserDN=strParameterValue;

if(strParameterName.ToUpper().Equals("GROUPNAME"))

strGroupName=strParameterValue;

if(strParameterName.ToUpper().Equals("ACCOUNTFILTER"))

strAccountFilter=strParameterValue;

                             }

                   }

                   //Search for user

                   DirectoryEntry deSystem = new DirectoryEntry("LDAP://" + strServerName + "/" + strUserDN + ","
                                                       + strBaseDN);

                   deSystem.AuthenticationType=AuthenticationTypes.Secure;

                   deSystem.Username=txtUserName.Text;

                   deSystem.Password =txtPassword.Text;

                   //Search for account name

                   string strSearch=strAccountFilter + "=" + txtUserName.Text;

                   DirectorySearcher dsSystem = new DirectorySearcher(deSystem,strSearch);

                   //Search subtree of UserDN

                   dsSystem.SearchScope= SearchScope.Subtree;

                   //Find the user data

                   SearchResult srSystem = dsSystem.FindOne();

                   //Pick up the user group belong to

                   ResultPropertyValueCollection valcol = srSystem.Properties["memberOf"];

                   if(valcol.Count>0)

                   {

                             foreach( object o in valcol )

                             {

                                      //check user exist in Group we are searching for

                                       if(o.ToString().Equals(strGroupName+","+strBaseDN))

                                      {

                                                blnGroupUser=true;

                                                break;

                                      }

                             }

                   }

                   if(blnGroupUser==true)

                             MessageBox.Show("Login Sucessfull...");

                   else

                             MessageBox.Show("User Does Not Belong to Specified ADSI Group");

          }

          catch(Exception ex)

          {

                    MessageBox.Show(ex.Message);

          }

          i=i+1;

          if(i==5)

          {

                    MessageBox.Show("Login failed for 5 times. Quiting...");

                    this.Close();

}

}

If everything works fine then you will get the message "Login Successful". If user does not belong to group specified in LDAP properties then will the message "User Does Not Belong to Specified ADSI Group". If you enter wrong user/pass, you will get Logon failure message.

Login Using Simple Database Table

You can also give the permission to the user, who are not domains user and wants to use your software. For this we can simply use traditional database LOGIN table.

CREATE TABLE [dbo].[LOGIN] (
 [USERNAME] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
 [PASSWORD] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

And admin can enter the username/password in table. And when user selects simple database login option from Login dialog, we can simply check against LOGIN table.

Code for GeDatabaseLogin function.

public void GetDatabaseLogin()

{

          //Data source string

          string source = "Data Source=ATHAKUR;Initial Catalog=Times;user=sa;password=sa" ;

          //SQL statement that will be issued

          string select = "SELECT * from LOGIN where USERNAME='" + txtUserName.Text + "'And PASSWORD
                               COLLATE Latin1_General_CS_AS='" + txtPassword.Text + "'";

          //SQL Connection

          SqlConnection conn=new SqlConnection(source);

          // Open the database connection

          conn.Open () ;

          // Create the SQL command...

          SqlCommand cmd = new SqlCommand ( select , conn ) ;

          //Execute Data reader

          SqlDataReader myReader = cmd.ExecuteReader();

          //Check if any rows return against user/pass

          if(myReader.HasRows)

                   MessageBox.Show("Login Sucessfull");

          else

                   MessageBox.Show("Login Failed");

                    //Close datareader and connection

                    myReader.Close();

                   conn.Close () ;

                   //check for % attempts

                   i=i+1;

                   if(i==5)

                   {

                             MessageBox.Show("Login failed for 5 times. Quiting...");

                             this.Close();

                   }

}

If user/pass does exist in database then you will get the message "Login successful", otherwise "Login failed" message will be displayed.

Conclusion

We have seen here, how System.DirectoryServices searches the LDAP directory for a user object and validate that against groups. One single domain login user/pass can be used to access the your software. And how SDS manages resources under Windows Active Directory Services.

Aah! Another bug! Well, it's the life.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Anand Thakur

 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Nice Article Ever on .NET by Manoj On July 3, 2006

Hi Dude,

Thakur saheb keep it up....

Reply | Email | Modify 
re : Authenticate a user against the Active Directory by Einstein On July 5, 2006

Went through u'r article and it was good. I have one doubt...

Consider that I'm having a list of user names and i need to check if they exist in a specific domain. Its not like authenticating the user but just check for their existence (without password check).

Rgds
Einstein

Reply | Email | Modify 
Re: re : Authenticate a user against the Active Directory by Anand On July 6, 2006

Hi Einzteen

Yes, you can search the active directory for users.

Regards
Anand

Reply | Email | Modify 
a question ? by Moustafa On August 17, 2006

Dear anand,

this is really good article,but how can i get some information from the active directory like the user country,city.......etc.

 

Reply | Email | Modify 
Re: Authenticate a user against the Active Directory by Tina On September 1, 2006

 

Hello Anand,

Your article is really wonderful afte a long time ..I have got to know AD from your code only.Great!

Do I need to create the table which stores the path of the Active Directory.

I have created a website and user dont have any login page.I need to authenticate the user directory through windows.If I get the username from your code.Can I get the Full Name of the user too???

How can I test the code from my lcoal machine...without specifing active directory server name??

Regards,

Reply | Email | Modify 
Not really authtenticating by Joey On October 5, 2006

Hello,

The code that u posted in your article isn't really authtenticating. It only checks if a given username exists in a group on the Active Directory server.

Because if I comment out the next part of the code than it works also. This means there's no authentication with the Active Directory server!

deSystem.Password =txtPassword.Text;

 

Greets Joey

Reply | Email | Modify 
Re: Not really authtenticating by Peter On October 22, 2009
It really does authenticate.  Instead of commenting out the password, try using an invalid password.
Reply | Email | Modify 
Can this be adapted to ASP.NET by Jagannatha On September 16, 2007
Kai se he!!! (poor Hindi) I am trying to learn C# with ASP.NET, by building a small Intranet web site for managing leave requests. I would like to be able to use AD authentication for all users to allow them in to specific areas. Like Managers to approve leave, Admin to aover see the Intranet site and general users to request leave. Any URL's to help me achieve learning this would go down well :-) Jagannatha Suta Das
Reply | Email | Modify 
ASP Code To authenticate user against Active Directory by ron On November 3, 2007
Hello Mr. Anand, Firstly thank you for above info, I am hopping, you be able to help me with following: I am designing a ASP page page allows user to enter user name and password and authenticate against Active directory services. And once user authenticated on ADS than it will let user into site Else access denied I am more on networking and have very basic knowledge about ASP, Would you be able to help me for this thank you, What code / how do I integrate with html I really appreciate your help, regards, Ron
Reply | Email | Modify 
Re: ASP Code To authenticate user against Active Directory by Thomas On March 6, 2008
Reply | Email | Modify 
Help by Luis On March 14, 2008
In "memberOf", what do I put?
Reply | Email | Modify 
Saved me a day or more by Mahesh On June 7, 2010

Great job Anand. Learned a lot from it and it saved me days.

Reply | Email | Modify 
Extra data in active directory like we do have in profiel for a member by prem On December 3, 2010
can we keep extra data in active directory like suppose branch for an user
Thanks,

Reply | Email | Modify 
Nice Article by Alok On September 7, 2011
Good Article, Thanks
Reply | Email | Modify 
my opinion by John On September 11, 2011
People who write such code examples should burn in hell, really...
Reply | Email | Modify 
A referral was returned from the server. by Raveendra On September 15, 2011
Hi Anand, i have writen same what ever u r provided code and testing in windows server 2008,but i am getting error ' A referral was returned from the server.' can u plase tell me what's the probelm. Regards Raveendra Reddy C
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.