Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 804
  • Last Modified:

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

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
d_chenxin
Asked:
d_chenxin
  • 5
  • 3
1 Solution
 
MogalManicCommented:
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
 
MogalManicCommented:
oops! typo.  Fix this block of code:
            search.PropertiesToLoad.Add("sAMAccountName");
            search.PropertiesToLoad.Add("memberof");
            search.PropertiesToLoad.Add("cn");
            search.PropertiesToLoad.Add("FullName");
0
 
d_chenxinAuthor Commented:
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
MogalManicCommented:
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
 
MogalManicCommented:
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
 
d_chenxinAuthor Commented:
Thank you so much!
0
 
MogalManicCommented:
So It worked?
0
 
d_chenxinAuthor Commented:
Yes, it works now, thanks again:>
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now