How to validate username and password through LDAP using C#?

Posted on 2006-06-14
Last Modified: 2011-10-03
I have the following code for validate username and password through LDAP, how can I rewrite it using C#? pls. help, thanks a lot!
Or can I use other methods to achieve this function, such as use System.DirectoryServices.

Function iPlanetAuth(strCoreID, strPassword)

         On Error Resume Next
         Dim oCon, oCmd, oRs, intCount
         Dim oUser, oADSObj, strUserDN, strAdsPath, oA

          Set oCon = Server.CreateObject("ADODB.Connection")
         Set oCmd = Server.CreateObject("ADODB.Command")
         oCon.Provider = "ADsDSOObject"
         oCon.Open "Active Directory Provider"
         Set oCmd.ActiveConnection = oCon
         oCmd.CommandText = "SELECT AdsPath FROM 'LDAP://,ou=intranet,dc=abc,dc=com' " & _
                   "WHERE uid='" & strCoreID & "'"
         oCmd.Properties("SearchScope") = 2      ' ADS_SCOPE_SUBTREE
         Set oRs = oCmd.Execute()
         if Not (oRs Is Nothing) then
                   intCount = oRs.RecordCount
                   if (intCount = 1) then
                            strAdsPath = oRs.Fields("adspath").Value
                            oA = Split(strAdsPath, "/")
                            strUserDN = oA(3)
                            Set oADSObj = GetObject("LDAP:")
                            Set oUser = oADSObj.OpenDSObject(CStr(strAdsPath), CStr(strUserDN), CStr(strPassword), 0)
                            if Err.Number <> 0 Then
                                     iPlanetAuth = false
                                     iPlanetAuth = true
                            end if
                            iPlanetAuth = false
                            ' too many matching users.
                   end if
                   iPlanetAuth = false
                   ' Cannot retrieve search result.
         end if
         Set oCon = nothing
         Set oCmd = nothing
         Set oRs = nothing
         Set oUser = nothing
         Set oADSObj = nothing
End Function
Question by:d_chenxin
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
LVL 21

Expert Comment

ID: 16902315
Try this:
    public override bool ValidateUser(string username, string password)
        //If username/password is authorized to read path, then it is correct
        DirectoryEntry ldapDir = new DirectoryEntry("LDAP://,ou=intranet,dc=abc,dc=com", username, password);

        DirectorySearcher search = new DirectorySearcher(ldapDir);

            search.Filter = "sAMAccountName=" + username;

            SearchResult result = search.FindOne();    //Read the path
            foreach (string group in result.Properties["memberof"])
                System.Diagnostics.Debug.WriteLine("group:" + group);
                //Could cache groups here with  search.FindAll() and load list of 'memberof' results

            //If you got this far then you are authorized!
            return true;
        catch (Exception ex)
            System.Diagnostics.Debug.WriteLine("NotAuthorized:" + username + ":" + ex.Message);
            return false;

add to top of class
using System.DirectoryServices;  //Add 'System.DirectoryServices' as a new reference as well
LVL 21

Expert Comment

ID: 16902328
oops! typo.  Fix this block of code:

Author Comment

ID: 16908373
Many thanks!

But when I run the program, it throws exception message "The requested authentication method is not supported by the server"  after run the first row code DirectoryEntry ldapDir = new DirectoryEntry("LDAP://,ou=intranet,dc=abc,dc=com", username, password);

I change the usename and password, the result is same, so I think it isn't username problem, may be the sever don't provide this kind of method?

But using VB code I posted before, it works fine. Pls. give me some advise. Thanks in advance.

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

LVL 21

Expert Comment

ID: 16910135
I'm sorry, I incorrectly assumed that it is Active Directory.

If you meant LDAP (which is the same but different), then you could try LDAPConnection class.  It is in the System.DirectoryServices.Protocols namespace (I think it is a seperate library as well).

Manual pages:

LVL 21

Accepted Solution

MogalManic earned 500 total points
ID: 16910214
Try this code:
Binding using an Identity

// C# Library namespace
using System.DirectoryServices.Protocols;

// Creating an LdapConnection instance
LdapConnection ldapConn= new LdapConnection("LDAP://,ou=intranet,dc=abc,dc=com");

NetworkCredential myCred = new NetworkCredential();
myCred .Domain = "";  //?might not need port number
myCred .UserName = UserName;
myCred .Password = Password;
//Bind function will Bind the user object Credentials to the Server

Author Comment

ID: 16917095
Thank you so much!
LVL 21

Expert Comment

ID: 16917315
So It worked?

Author Comment

ID: 16918098
Yes, it works now, thanks again:>

Featured Post

Want Experts Exchange at your fingertips?

With Experts Exchange’s latest app release, you can now experience our most recent features, updates, and the same community interface while on-the-go. Download our latest app release at the Android or Apple stores today!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor ( Top Charts is a view in which you can set seve…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question