Code Robo
Formatter
Comparator
Tester
Merger
Converter
Utility
Java Code Complience
Validator
EncoderDecoder
Virtual Service
Java Code To Authenticate An User In LDAP Server /AD / ED
       Talk to EasyAssistant

Java Authenticate Functions authenticate an user in LDAP server / Acttive Directory (AD) / ED. It shows basic java code to connect to corporate LDAP server and authorize an user against his/her password. It can be copied and used any other java java project. It uses javax naming api class .


Java Code To Connect LDAP server and Authorize an user using his credentials
 package com;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.OperationNotSupportedException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.InvalidAttributeValueException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class Auth {

	private java.util.Properties propManager = getPropManager();
	private String ldapUrl = null; // e.g. ldaps://app1.easycodeforall.com:1637

	public Auth() {
		ldapUrl = propManager.getProperty("secure.provider.url");
	}

	/**
	 * 
	 * 
	 * 
    *
  1. Acquire admin LDAP server Connection
  2. *
  3. Search the Directory for the given userid
  4. *
  5. Authenticate the user for the password.
  6. *
* * @throws Exception - Always throws exception if authentication is not * successful. * */ public final Map authenticate(final String userid, final String password) throws Exception { System.out.println("userid = " + userid); DirContext ctxAdmin = null; String networkId = null; NamingEnumeration searchResults = null; // Warning message like "Password will expire in next one month" will be stored // in // this map. This message may be useful to dispaly displayed in UI. Map messageMap = new HashMap(); try { networkId = userid; // Get admin InitialDirectoryContext using Admin credentials ctxAdmin = this.getAdminIniDirectoryCtx(); System.out.println("Admin connection to LDAP server is successful"); // // Search the directory in LDAP server using admin context to know whether user // present or not searchResults = getADSearchResult(ctxAdmin, networkId); if (!searchResults.hasMore()) { throw new Exception("ERROR_CODE_100SR"); } System.out.println("Search result successful for the user " + networkId); // Authenticate the user in LDAP server using his password this.authenticateInLdapServer(searchResults, networkId, password); System.out.println(" Auth is Successful for userid = " + userid); } catch (Exception authEx) { System.out.println("Auth is notsuccessful : " + userid); System.out.println("=authEx=" + authEx); authEx.printStackTrace(); } finally { try { if (searchResults != null) { searchResults.close(); } } catch (Exception closeEx) { System.out.println("Error in closing the SearchResult : " + closeEx.getMessage()); } this.closeDirectoryCtx(ctxAdmin); } return messageMap; } /** * This method authenticate a user using his password in the LDAPServer. * * @throws Exception If Auth fails. * */ private void authenticateInLdapServer(final NamingEnumeration searchResults, final String networkid, final String password) throws Exception { InitialDirContext authenticatingContext = null; try { SearchResult result = searchResults.next(); // Get the basic LDAP properties Hashtable newEnv = this.getEnvProperty(); // --LDAP Security Principal the user // e.g. employeeNumber=easycd5,ou=people,ou=americas String securityPrincipal = result.getName(); System.out.println("securityPrincipal value=" + securityPrincipal); // e.g. employeeNumber=easycd5,ou=people,ou=americas,dc=easycodeforall,dc=com newEnv.put(Context.SECURITY_PRINCIPAL, securityPrincipal + "," + propManager.getProperty("base.search")); newEnv.put(Context.SECURITY_CREDENTIALS, password); authenticatingContext = new InitialDirContext(newEnv); if (authenticatingContext == null) { System.out.println("Unable to get InitialDirContext for password validation"); System.out.println("authenticatingContext is null"); throw new Exception("authenticatingContext IS NULL"); } } catch (AuthenticationException authEx) { System.out.println(authEx); throw new Exception("Invalid Password"); } catch (InvalidAttributeValueException authEx) { System.out.println(authEx); throw new Exception("Password Locked"); } catch (OperationNotSupportedException authEx) { System.out.println(authEx); throw new Exception("User Is Inactive In Active Directory(LDAP)"); } catch (Exception ex) { System.out.println(ex); throw new Exception("Exception in LDAP authentication"); } finally { this.closeDirectoryCtx(authenticatingContext); } } /** * This method establish a connection with the LDAP Server using Admin user * * @return * @throws Exception If LDAP Server is not reachable */ private InitialDirContext getAdminIniDirectoryCtx() throws Exception { InitialDirContext ctx = null; try { // No need to add admin credantial . // Binding and searching can be done anonimously in LDAP server. ctx = new InitialDirContext(this.getEnvProperty()); System.out.println("Admin Connection to LDAP server is successfull."); return ctx; } catch (Exception ex) { System.out.println(ex); throw new Exception("LDAP server not reachable=" + ex); } } /** * This method is used to search the LDAP sever directory and it returns result * as enumeration. * * @param ctx Initial Directory Context for ADMIN * @param loginID corporate Networkid of the user. * @return Directory search result. * * @throws Exception Custom Exception */ private NamingEnumeration getADSearchResult(final DirContext ctx, final String lanID) throws Exception { SearchControls searchControls = new SearchControls(); try { searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // e.g.filter = "uid="; String filter = propManager.getProperty("dirictory.filter.critera") + lanID; // Search the LDAP server tree for the user starting at the root context return ctx.search(propManager.getProperty("base.search"), filter, searchControls); } catch (Exception ex) { System.out.println(ex); throw ex; } } private void closeDirectoryCtx(final DirContext ctx) { try { if (ctx != null) ctx.close(); } catch (Exception e) { System.out.println(" Error in closing is:" + e.getMessage()); } } private Hashtable getEnvProperty() { Hashtable ldapProp = new Hashtable(); ldapProp.put(Context.INITIAL_CONTEXT_FACTORY, propManager.getProperty("initial.context.factory")); ldapProp.put(Context.PROVIDER_URL, ldapUrl); // Default LDAP version is 3 ldapProp.put(propManager.getProperty("ldap.version.name"), propManager.getProperty("ldap.version.value")); ldapProp.put(Context.SECURITY_AUTHENTICATION, propManager.getProperty("security.authentication")); return ldapProp; } private static Properties getPropManager() { Properties prop = new Properties(); prop.put("initial.context.factory", "initial.context.factory"); prop.put("ldap.version.name", "java.naming.ldap.version"); prop.put("ldap.version.value", "3"); prop.put("security.authentication", "simple"); prop.put("security.credentials", "XYZB679HK36M"); prop.put("nonadmin.security.principal.1", "employeenumber"); prop.put("nonadmin.security.principal.2", ",ou=people,ou=americas"); prop.put("security.principal", "uid=easycodeforalldm,ou=applications,dc=easycodeforall,dc=com"); prop.put("secure.provider.url", "ldaps://app3.easycodeforall.com:16243"); prop.put("non.secure.provider.url", "ldap://app3.easycodeforall.com:1120"); return prop; } }



Note: If you are getting exception to Please check the exception message details.
  1. Please double cheeck LDAP server URL and password you are passing.



Post Your Comment:
Name :
Email ( Optional) :
Comments / Suggestion (* Required) It is required: :
: