0

I have a C# code to connect to LDAP Server and it works perfectly fine

The working C# code is given below

        user = "myname@myorg.com";
        string pwd = "secret";

        String uid = "uid=" + user + ",ou=people,dc=myorg,dc=com";
        int empID = 0;
        DirectoryEntry root = new DirectoryEntry("LDAP://myorg.com", user, pwd, AuthenticationTypes.None);
        try
        {
            object connected = root.NativeObject;

            DirectorySearcher search = new DirectorySearcher(root);

            search.Filter = "(&(objectClass=user)(objectCategory=Person))";

            search.PropertiesToLoad.Add("SAMAccountName");
            search.PropertiesToLoad.Add("EmployeeID");

            foreach (System.DirectoryServices.SearchResult resEnt in search.FindAll())
            {
                System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();

                if (de.Properties["employeeID"].Value != null && de.Properties["userPrincipalName"].Value != null)
                {
                    if (user.Equals(de.Properties["userPrincipalName"].Value))
                    {
                        string empIDstr = (string)de.Properties["employeeID"].Value;

                        int.TryParse(empIDstr, out empID);
                        Response.Write("EMp ID is No is "+empID);
                    }

                }
            }
        }
        catch(Exception ex)
        {
            Response.Write("Logon failed");
        }

Now I am trying to do the same thing in java as I have another application to develop in Java but the following code throws exception

public class LdapClient {


    public void authenticate(String user, String pwd){

        String uid = "uid=" + user + ",ou=people,dc=myorg,dc=com";

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://myorg.com");
        env.put(Context.SECURITY_AUTHENTICATION, "none");
        env.put(Context.SECURITY_PRINCIPAL, uid);
        env.put(Context.SECURITY_CREDENTIALS, pwd);

        try {
            DirContext ctx = new InitialDirContext(env);

            **//THE ERROR COMES AT THE LINE BELOW**
            NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=myorg,dc=com", "(&(objectclass=user)(objectCategory=Person))", getSimpleSearchControls());
            **strong text**
            while (namingEnum.hasMore ()) {
                SearchResult result = (SearchResult) namingEnum.next ();    
                Attributes attrs = result.getAttributes ();
                System.out.println(attrs.get("cn"));

            } 
            namingEnum.close();
        } catch (Exception e) {
            try {
                e.printStackTrace();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    private SearchControls getSimpleSearchControls() {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = {"samAccountName","employeeID"};
        searchControls.setReturningAttributes(attrIDs);
        return searchControls;
    }

}

PLEASE HELP as I thing the corresponding same code works in C#

javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C09075A, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1 ]; remaining name 'ou=people,dc=myorg,dc=com'
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(Unknown Source)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
    at com.sun.jndi.ldap.LdapCtx.searchAux(Unknown Source)
    at com.sun.jndi.ldap.LdapCtx.c_search(Unknown Source)
    at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(Unknown Source)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(Unknown Source)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(Unknown Source)
    at javax.naming.directory.InitialDirContext.search(Unknown Source)
    at ldap.LdapClient.authenticate(LdapClient.java:51)
    at ldap.LdapClient.main(LdapClient.java:30)

I have to do this in Java as I need to develop another application pointing to the same LDAP server . The client needs to be java. PLEASE HELP

Nostalgic
  • 300
  • 1
  • 4
  • 18

1 Answers1

1

The exceptions says that it requires an authentication (bind) before performing the operation (search). As it's shown in the documentation try to use simple authentication

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");
  • What you suggested is already in place (please see below) `String uid = "uid=" + user + ",ou=people,dc=myorg,dc=com"; env.put(Context.SECURITY_PRINCIPAL, uid);` Also, in the corresponding C# code its `AuthenticationTypes.None`, so I used "none" in java for `Context.SECURITY_AUTHENTICATION` – Nostalgic Dec 28 '18 at 06:42
  • @RohitGaneshan From the documentation https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.authenticationtypes?view=netframework-4.7.2 AuthenticationTypes.None stands for 'simple bind' which is in Java specified by 'env.put(Context.SECURITY_AUTHENTICATION, "simple");' – Abylay Sabirgaliyev Dec 28 '18 at 07:11
  • I made the suggested changes but getting another error now `javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090400, comment: AcceptSecurityContext error, data 52e, v1db1 ]` – Nostalgic Dec 28 '18 at 10:47
  • It's an authentication exception, meaning there's some problem with username/password. Please, look here for possible solutions https://stackoverflow.com/questions/31411665/ldap-error-code-49-80090308-ldaperr-dsid-0c0903a9-comment-acceptsecurityc – Abylay Sabirgaliyev Dec 28 '18 at 10:55
  • I was able to login to the server by trying the answers in the above thread.But it became a bit odd.. generally we login to LDAP using the unique username or email, like `cn=myname@myorg.com`..but in this case I was able to login to the server only after i gave `cn=Full Name`, this was one of the workarounds suggested in the above thread.. so, for example `cn=Ross Buttler` worked where as the username `cn=rbutler` will not work.. but there can be two people with the same full name "Ross Buttler"..so how ll the system uniquely identify which is the user concerned?The issue exists in Java not C# – Nostalgic Dec 31 '18 at 09:18
  • Any solution for the above mentioned issue, ie full name vs unique username, is welcome.. – Nostalgic Jan 02 '19 at 04:46
  • I would suggest this solution https://stackoverflow.com/questions/35349256/java-ldap-authentication-with-username – Abylay Sabirgaliyev Jan 04 '19 at 13:52
  • @AbylaySabirgaliyev Can't I use AD just for authorization hence not providing username and password and using "none" in SECURITY_AUTHENTICATION ? I am getting same error for binding using Anonymous Authentication when I am searching for a user in AD. – coderzzz18 Jan 14 '20 at 07:52