Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

LDAP Connection

Gökberk Karaca August 4, 2022

Hello, 

I need to establish a LDAPS connection. I wrote a getLdapContext method but it returns null. Here is my code: 

private static LdapContext getLdapContext() {
LdapContext ctx ;
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
env.put(Context.SECURITY_PRINCIPAL, *****);//input user & password for access to ldap
env.put(Context.SECURITY_CREDENTIALS, *******);
env.put("java.naming.ldap.factory.socket", "MySSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.PROVIDER_URL, "****");
env.put(Context.REFERRAL, "follow");
ctx = new InitialLdapContext(env, null);
System.out.println("LDAP Connection: COMPLETE");
} catch (NamingException nex) {
System.out.println("LDAP Connection: FAILED");
nex.printStackTrace();
}
return ctx;
}

 

What am I doing wrong here?


Thanks.

1 answer

1 accepted

Suggest an answer

Log in or Sign up to answer
1 vote
Answer accepted
Agustin G_ Leguizamón Pondal August 4, 2022

I tried this with a LDAP from https://www.forumsys.com/, and works like a charm:

import java.util.Hashtable;
import
javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class LdapContextCreation {
    public static void main(String[] args) {
        LdapContextCreation ldapContxCrtn = new LdapContextCreation();
        LdapContext ctx = ldapContxCrtn.getLdapContext();
    }
    public LdapContext getLdapContext(){
        LdapContext ctx = null;
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,  "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");  
        env.put(Context.SECURITY_PRINCIPAL, "cn=read-only-admin,dc=example,dc=com");        
        env.put(Context.SECURITY_CREDENTIALS, "password");          
        env.put(Context.PROVIDER_URL, "ldap://ldap.forumsys.com:389/");
        try{
        ctx = new InitialLdapContext(env, null);          
        System.out.println("Connection Successful.");  
        }catch(NamingException nex){      
            System.out.println("LDAP Connection: FAILED");      
            nex.printStackTrace();
        }      
        return ctx;
    }
}
TAGS
AUG Leaders

Atlassian Community Events