Wednesday, July 09, 2008

LDAP Search : Search for a user in Oracle Internet Directory

The need to search for a user's entry in Oracle Internet directory (OID) crops up very often in various situations.

You can easily do this using JNDI. You need to usually take care of these things before we proceed with the code :-

1. You have access to Oracle Internet Directory.

2. You know the Distinguished Name ( DN ) of the entry that is the immediate parent of all the users.

3. You know the attribute used to search. E.g.: cn, mail, sn, etc.

4. You know that the attribute used to search has been "indexed" by Oracle Internet Directory.
You can then adapt this piece of code to suit your needs & look for users - the lines marked in red are important :-

String strSearchString = "sandeep";

String strLDAPUrl = "ldap://localhost:389";

String strUserRootDN = "cn=Users,dc=test,dc=com";
String strFilter = "cn="+strSearchString ;

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, strLDAPUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");

// You know the credentials to search in OID
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "mySecretPassword");

try
{

DirContext ctx = new InitialDirContext(env);
Attributes attrs = ctx.getAttributes(strUserRootDN,strFilter,new String[]{"mail"});

Attribute attr = attrs.get("mail");
System.out.println(attr.get());

ctx.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
You can easily modify this piece of code to search for users in a group, etc.

No comments: