LDAP Connection Sample Java

LDAP Connection Sample Java demo program show how to connect LDAP server. Please use this

program and replace your LDAP domain name and port number and it also need valid user id and password to access the record from LDAP server.

LDAP Connection Sample Java sample code:

package com.ldap;

import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;

public class LDAPConnectionSample {
	public static String ldapUri = "ldap://domainName";
	public static String usersContainer = "cn=users,DC=pte-am,DC=companyName,DC=com";

	public static void main(String args[]) {

		String username = "domainName\\userid";
		String password = "password";

		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, ldapUri);
		env.put(Context.SECURITY_PRINCIPAL, username);
		env.put(Context.SECURITY_CREDENTIALS, password);

		try {
			DirContext ctx = new InitialDirContext(env);
			SearchControls ctls = new SearchControls();
			String[] attrIDs = { "cn" };
			ctls.setReturningAttributes(attrIDs);
			ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);

			NamingEnumeration answer = ctx.search(usersContainer,
					"(objectclass=group)", ctls);
			while (answer.hasMore()) {
				SearchResult rslt = (SearchResult) answer.next();
				Attributes attrs = rslt.getAttributes();
				System.out.println(attrs.get("cn"));
			}
			ctx.close();

		} catch (NamingException e) {
			e.printStackTrace();
		}

	}
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *