Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » 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.

Total page views :  42098
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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.

 

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 Sub btnSubmit_Click(sender As Object, e As EventArgs)

      If txtUserName.Text.Trim().Equals("") OrElse txtPassword.Text.Trim().Equals("") Then

         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 Then

            GetADSILogin()

         Else

            GetDatabaseLogin()

         End If

      End If

End Sub 'btnSubmit_Click

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

Public Sub GetADSILogin()

      Try

         Dim strServerName As String = ""

         Dim strBaseDN As String = ""

         Dim strUserDN As String = ""

         Dim strGroupName As String = ""

         Dim strAccountFilter As String = ""

         'Port no for LDAP Default is 389

         Dim strPortNo As String = "389"

         Dim blnGroupUser As [Boolean] = False

         'Data source string

         Dim [source] As String = "Data Source=ATHAKUR;Initial Catalog=Times;user=sa;password=sa"

        

         'SQL statement that will be issued

         Dim [select] As String = "SELECT * from ADSI_PARAMETER"        

         'SQL Connection

         Dim conn As New SqlConnection([source])        

         ' Open the database connection

         conn.Open()        

         ' Create the SQL command...

         Dim cmd As New SqlCommand([select], conn)        

         'Execute Data reader

         Dim myReader As SqlDataReader = cmd.ExecuteReader()        

         'Check if any rows return against user/pass

         If myReader.HasRows Then

            While myReader.Read()

               'Store the parameter's data in variables

               Dim strParameterName As String = myReader.GetString(0).Trim()

               Dim strParameterValue As String = myReader.GetString(1).Trim()

               If strParameterName.ToUpper().Equals("SERVERNAME") Then

                  strServerName = strParameterValue

               End If

               If strParameterName.ToUpper().Equals("BASEDN") Then

                  strBaseDN = strParameterValue

               End If

               If strParameterName.ToUpper().Equals("USERDN") Then

                  strUserDN = strParameterValue

               End If

               If strParameterName.ToUpper().Equals("GROUPNAME") Then

                  strGroupName = strParameterValue

               End If

               If strParameterName.ToUpper().Equals("ACCOUNTFILTER") Then

                  strAccountFilter = strParameterValue

               End If

            End While

         End If 'Search for user

         Dim deSystem As New DirectoryEntry("LDAP://" + strServerName + "/" + strUserDN + "," + strBaseDN)

         deSystem.AuthenticationType = AuthenticationTypes.Secure

         deSystem.Username = txtUserName.Text

         deSystem.Password = txtPassword.Text

         'Search for account name

         Dim strSearch As String = strAccountFilter + "=" + txtUserName.Text

         Dim dsSystem As New DirectorySearcher(deSystem, strSearch)

         'Search subtree of UserDN

         dsSystem.SearchScope = SearchScope.Subtree

         'Find the user data

         Dim srSystem As SearchResult = dsSystem.FindOne()

         'Pick up the user group belong to

         Dim valcol As ResultPropertyValueCollection = srSystem.Properties("memberOf")

         If valcol.Count > 0 Then

            Dim o As Object

            For Each o In  valcol

               'check user exist in Group we are searching for

               If o.ToString().Equals((strGroupName + "," + strBaseDN)) Then

                  blnGroupUser = True

                  Exit ForEach

               End If

            Next o

         End If

         If blnGroupUser = True Then

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

         Else

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

         End If

      Catch ex As Exception

         MessageBox.Show(ex.Message)

      End Try

      i = i + 1

      If i = 5 Then

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

         Me.Close()

      End If

   End Sub 'GetADSILogin

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 Sub GetDatabaseLogin()

      'Data source string

      Dim [source] As String = "Data Source=ATHAKUR;Initial Catalog=Times;user=sa;password=sa"

      'SQL statement that will be issued

      Dim [select] As String = "SELECT * from LOGIN where USERNAME='" + txtUserName.Text + "'And PASSWORD "

      Dim Latin1_General_CS_AS As COLLATE = ControlChars.Quote + txtPassword.Text + "'" '

      'SQL Connection

      Dim conn As New SqlConnection([source])

      ' Open the database connection

      conn.Open()

      ' Create the SQL command...

      Dim cmd As New SqlCommand([select], conn)

      'Execute Data reader

      Dim myReader As SqlDataReader = cmd.ExecuteReader()

      'Check if any rows return against user/pass

      If myReader.HasRows Then

         MessageBox.Show("Login Sucessfull")

      Else

         MessageBox.Show("Login Failed")

      End If 'Close datareader and connection

      myReader.Close()

      conn.Close()

      'check for % attempts

      i = i + 1

      If i = 5 Then

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

         Me.Close()

      End If

   End Sub 'GetDatabaseLogin

 

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.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/). 


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
Access 2003 by Adrian On July 30, 2007
Can this be implemented using VBA and Access 2003? I mean, can I make calls to the LDAP from Visual Basic for Applications? Thanks for your attention.
Reply | Email | Delete | Modify | 
Hi from Italy... by luca On February 11, 2008
Have a similar soltion in VB calssic? tks.
Reply | Email | Delete | Modify | 
Hi from Italy... by luca On February 11, 2008
Have a similar soltion in VB calssic? tks.
Reply | Email | Delete | Modify | 
Question by Luis On March 17, 2008
This line, Dim valcol As ResultPropertyValueCollection = srSystem.Properties("memberOf"), it does not work, why?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.