To use anonymous access for an LDAP search or query set the value of Context.SECURITY_AUTHENTICATION to “none” in the environment used to create the initial context.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, providerUrl);
// Use 'none' for anonymous access
env.put(Context.SECURITY_AUTHENTICATION, "none");
// Create the initial context
DirContext ctx = new InitialDirContext(env);
written by objects
\\ tags: authentication, ldap, query, search
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: authentication, DirContext, ldap, simple