Mar 06
import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class SimpleLdapAuthentication
{
	public static void main(String[] args)
	{
		String username = "user";
		String password = "password";
		String base = "ou=People,dc=objects,dc=com,dc=au";
		String dn = "uid=" + username + "," + base;
		String ldapURL = "ldap://ldap.example.com:389";

		// Setup environment for authenticating
		
		Hashtable<String, String> environment = 
			new Hashtable<String, String>();
		environment.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		environment.put(Context.PROVIDER_URL, ldapURL);
		environment.put(Context.SECURITY_AUTHENTICATION, "simple");
		environment.put(Context.SECURITY_PRINCIPAL, dn);
		environment.put(Context.SECURITY_CREDENTIALS, password);

		try
		{
			DirContext authContext = 
				new InitialDirContext(environment);
			
			// user is authenticated
			
		}
		catch (AuthenticationException ex)
		{
			
			// Authentication failed

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

written by objects \\ tags: , , ,


4 Responses to “An example of simple ldap authentication”

  1. deepa Says:

    hi.. this program is not running in my application. i am gettingjavax.naming.InvalidNameException: [LDAP: error code 34 – invalid DN] exception..

    please can u suggest me where i went wrong

  2. objects Says:

    Check that your dn is correct

  3. fabio Says:

    You need to configure your ldif correctly. It most contain exactly the same data in the archive.

  4. Yosimar Says:

    Hi, I try with environment.put(Context.SECURITY_PRINCIPAL,user@objects.com.au]);
    and I can do log in.

    I hope help

Leave a Reply

You must be logged in to post a comment.