Active Directory Authentication using Java or Connecting to AD using java ( JNDI)


// Common Settings are     

 localHashtable.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
        localHashtable.put("java.naming.security.authentication", "simple");
        localHashtable.put("com.sun.jndi.ldap.connect.pool", "true");
        localHashtable.put("com.sun.jndi.ldap.connect.pool.timeout", "60000");
        localHashtable.put("java.naming.referral", "follow");
//
        StringBuffer localStringBuffer = new StringBuffer();
        // Check whether the SSL is ON or OFF, Change the url based on that
        if(SSLON) // @Sekhar removed SSL for time being
        {
            localStringBuffer.append("ldaps://");
            localHashtable.put("java.naming.security.protocol", "ssl");
        } else
        {
            localStringBuffer.append("ldap://");
        }

        localStringBuffer.append(AdSynchPropertiesEnum.AD_SERVER.getValue()).append(":")
        .append(AdSynchPropertiesEnum.AD_PORTNUMBER.getValue()).append("/");

// Here based on the username provided, we need to build the protocol string
// If only we are taking username and appending the domain name to it, then do it as like this
// Cause domain name may contain the sub domain also. This way, the string will build as like,
// CN=username, CN=Users, DC=domain name, DC=com
// Considering the user with username resides in CN=Users container.
        /*String[] domainName = AdSynchPropertiesEnum.AD_DOMAINNAME.getValue().split("\\.");
        StringBuilder principalValue = new StringBuilder("CN=").append(AdSynchPropertiesEnum.AD_ADMINISTRATOR.getValue())
                .append(",CN=Users");
        for(int i=0;i<domainName.length;i++)
        {
            principalValue.append(",DC=").append(domainName[i]);
        }*/
     
// Or else we can read the total string as username like CN=Admin, CN=Users, DC=domain,
// DC=com
// Or the simplest way is take plain username and append the domain name to it using @
// username@dominaname  admin@ad.watchmouse.com  like that.

        localHashtable.put("java.naming.provider.url", localStringBuffer.toString());
        localHashtable.put("java.naming.security.principal", AdSynchPropertiesEnum.AD_ADMINISTRATOR.getValue());
        localHashtable.put("java.naming.security.credentials", AdSynchPropertiesEnum.AD_PASSWORD.getValue());

        localInitialLdapContext = new InitialLdapContext(localHashtable, null);