Search code examples
javaldapjndiopenldap

How Can i connect to an LDAP server using following details from java?


I am having following java code but i am getting error provided details

password="some"; domain name=ABF.ADDAS.com user name=SADFA.com\username or SADFA\username

Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, "ldap://ip:389");
            // 
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, ""); 
            env.put(Context.SECURITY_CREDENTIALS, "password");

Solution

  • Just call InitialLdapContext with your parameters:

    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, domainName + "\\" + username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    
    try{
        return new InitialLdapContext(env, null);
    }
    catch(javax.naming.CommunicationException e){
        throw new NamingException("Failed to connect to " + domainName + ((serverName==null)? "" : " through " + serverName));
    }
    catch(NamingException e){
        throw new NamingException("Failed to authenticate " + username + "@" + domainName + ((serverName==null)? "" : " through " + serverName));
    }