Saturday, 29 May 2021

Java: Get LDAPConnection object

LDAPConnection object can be created using LDAPConnection class.

 

Follow below step-by-step procedure to get LDAPConnection object.

 

Step 1: Define LDAPConnectionOptions object.

LDAPConnectionOptions ldapConnectionOptions = new LDAPConnectionOptions();
ldapConnectionOptions.setResponseTimeoutMillis(10000);
ldapConnectionOptions.setUseSynchronousMode(true);
ldapConnectionOptions.setAllowConcurrentSocketFactoryUse(true);
ldapConnectionOptions.setConnectTimeoutMillis(10000);
ldapConnectionOptions.setAbandonOnTimeout(true);
ldapConnectionOptions.setBindWithDNRequiresPassword(false);

 

Step 2: Get an instance of SSLSocketFactory.

TrustAllTrustManager allTrustManager = new TrustAllTrustManager();
SSLUtil sslUtil = new SSLUtil(allTrustManager);
SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory();

Step 3: Get an instance of LDAPConnection.

LDAPConnection ldapConnection = new LDAPConnection(sslSocketFactory, ldapConnectionOptions, host, port, userName, password);


Find the below working application.

 

LDAPUtil.java

package com.sample.app.util;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.spi.NamingManager;
import javax.net.ssl.SSLSocketFactory;

import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPConnectionOptions;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;

public class LDAPUtil {

	private static final String LDAP_SERVICE_PREFIX = "dns:///_ldap";
	private static final String[] SRV_ID = { "SRV" };
	private static final String SRV_PROPERTY = "SRV";

	/**
	 * Example:
	 * LDAPUtil.getAllServersBehindThisObject("dns:///_ldap._tcp.ca.sample.com",
	 * 4); This logic will change based on the srvRecords format received from DNS
	 * 
	 * @param ldapDNSURL
	 * @param limitServers
	 * @return
	 * @throws NamingException
	 */
	public static List<String> getAllServersBehindThisObject(String ldapDNSURL, int limitServers)
			throws NamingException {

		if (ldapDNSURL == null || ldapDNSURL.isEmpty()) {
			throw new IllegalArgumentException("ldapDNSURL must not be empty");
		}

		if (!ldapDNSURL.startsWith(LDAP_SERVICE_PREFIX)) {
			throw new IllegalArgumentException("ldapDNSURL must start with " + LDAP_SERVICE_PREFIX);
		}

		List<String> serversBehindThisDNS = new ArrayList<>();

		DirContext context = (DirContext) NamingManager.getURLContext("dns", new Hashtable<String, Object>());
		Attributes attributes = context.getAttributes(ldapDNSURL, SRV_ID);
		Attribute srvRecords = attributes.get(SRV_PROPERTY);

		for (int i = 0; i < srvRecords.size(); i++) {
			if (i > limitServers - 1) {
				break;
			}

			String srvRecord = srvRecords.get(i).toString();
			String serverName = extractServerNameFromSRVRecord(srvRecord);

			if (serverName == null) {
				continue;
			}

			serversBehindThisDNS.add(serverName);

		}

		return serversBehindThisDNS;
	}

	public static LDAPConnection getLDAPConnection(final String host, final int port, final String userName,
			final String password) throws LDAPException, GeneralSecurityException {

		LDAPConnectionOptions ldapConnectionOptions = getDefaultLDAPConnectionOptions();
		SSLSocketFactory sslSocketFactory = getDefaultSSLSocketFactory();

		LDAPConnection ldapConnection = new LDAPConnection(sslSocketFactory, ldapConnectionOptions, host, port,
				userName, password);

		if (ldapConnection == null) {
			throw new IllegalArgumentException("Invalid username or password");
		}

		return ldapConnection;

	}

	public static SSLSocketFactory getDefaultSSLSocketFactory() throws GeneralSecurityException {
		TrustAllTrustManager allTrustManager = new TrustAllTrustManager();
		SSLUtil sslUtil = new SSLUtil(allTrustManager);

		return sslUtil.createSSLSocketFactory();

	}

	public static LDAPConnectionOptions getDefaultLDAPConnectionOptions() {
		LDAPConnectionOptions ldapConnectionOptions = new LDAPConnectionOptions();
		ldapConnectionOptions.setResponseTimeoutMillis(10000);
		ldapConnectionOptions.setUseSynchronousMode(true);
		ldapConnectionOptions.setAllowConcurrentSocketFactoryUse(true);
		ldapConnectionOptions.setConnectTimeoutMillis(10000);
		ldapConnectionOptions.setAbandonOnTimeout(true);
		ldapConnectionOptions.setBindWithDNRequiresPassword(false);
		return ldapConnectionOptions;
	}

	private static String extractServerNameFromSRVRecord(String srvRecord) {
		String[] splits = srvRecord.split(" ");

		if (splits.length != 4) {
			return null;
		}

		String server = splits[3];

		int lastCharIndex = server.lastIndexOf(".");
		if (lastCharIndex == server.length() - 1) {
			server = server.substring(0, server.length() - 1);
		}
		return server;

	}

}


HelloWorld.java

package com.sample.app;

import java.security.GeneralSecurityException;
import java.util.List;

import javax.naming.NamingException;

import com.sample.app.util.LDAPUtil;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;

public class HelloWorld {

	private static final String USER_NAME = "";
	private static final String PASSWORD = "";
	private static final String DOMAIN_NAME = "ca.sample.com";
	private static final String DOMAIN_NAME_WITH_LDAP_TCP = "_ldap._tcp." + DOMAIN_NAME;
	private static final String DOMAIN_NAME_WITH_LDAP_TCP_DNS = "dns:///" + DOMAIN_NAME_WITH_LDAP_TCP;

	public static void main(String args[]) throws GeneralSecurityException, LDAPException, NamingException {

		List<String> serversBehindThisDomain = LDAPUtil.getAllServersBehindThisObject(DOMAIN_NAME_WITH_LDAP_TCP_DNS, 4);

		LDAPConnection ldapConnection = LDAPUtil.getLDAPConnection(serversBehindThisDomain.get(0), 636, USER_NAME,
				PASSWORD);

		System.out.println("Connection Name : " + ldapConnection.getConnectionName());
		System.out.println("Connection IP Address : " + ldapConnection.getConnectedIPAddress());
		System.out.println("Connection Port: " + ldapConnection.getConnectedPort());

	}

}


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment