Solved

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

Posted on 2006-06-14
8
763 Views
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://acb.abc.com:389/ou=people,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
                            else
                                     iPlanetAuth = true
                            end if
                   else
                            iPlanetAuth = false
                            ' too many matching users.
                   end if
         else
                   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
0
Comment
Question by:d_chenxin
  • 5
  • 3
8 Comments
 
LVL 21

Expert Comment

by:MogalManic
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://acb.abc.com:389/ou=people,ou=intranet,dc=abc,dc=com", username, password);

        DirectorySearcher search = new DirectorySearcher(ldapDir);
        try
        {
            search.PropertiesToLoad.Add("sAMAccountName");
            search.PropertiesToLoad("memberof");
            search.PropertiesToLoad("cn");
            search.PropertiesToLoad("FullName");

            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
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 16902328
oops! typo.  Fix this block of code:
            search.PropertiesToLoad.Add("sAMAccountName");
            search.PropertiesToLoad.Add("memberof");
            search.PropertiesToLoad.Add("cn");
            search.PropertiesToLoad.Add("FullName");
0
 

Author Comment

by:d_chenxin
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://acb.abc.com:389/ou=people,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.

Sidney
0
 
LVL 21

Expert Comment

by:MogalManic
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:http://msdn2.microsoft.com/en-us/library/system.directoryservices.protocols.ldapconnection.aspx


0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 21

Accepted Solution

by:
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://acb.abc.com:389/ou=people,ou=intranet,dc=abc,dc=com");


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

Author Comment

by:d_chenxin
ID: 16917095
Thank you so much!
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 16917315
So It worked?
0
 

Author Comment

by:d_chenxin
ID: 16918098
Yes, it works now, thanks again:>
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

758 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now