|
Next: 10.2.6 Binding with a Up: 10.2 SIP Previous: 10.2.4 Public Variables Defined
|
The following code shows how to bind anonymously to the LDAP server
and searches for User Distinguished Name (DN) entered by a user. This
function is executed in Step 3 of Figure
.
public static String BindAnonymous(String LDAPHost,
String UsrID, String BaseDN) throws NamingException
{
try
{
String vLDAPHost = LDAPHost;
String vUsrID = UsrID;
String vBaseDN = BaseDN;
Hashtable anonymousEnv = new Hashtable();
/* Setting the environment for anonymous authentication */
anonymousEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
anonymousEnv.put(Context.PROVIDER_URL, vLDAPHost);
anonymousEnv.put(Context.SECURITY_AUTHENTICATION, "none");
/* Creating the directory context with anonymous environment
set above */
DirContext anonymousCtx = new
InitialDirContext(anonymousEnv);
/* Set the filter as the User DN provided by a user*/
String filter = "(&("+vUsrID+") )";
SearchControls ctls = new SearchControls();
/* Set the search scope for main as well as subtree nodes*/
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
/* Connecting to the directory anonymously and searching
for the User DN */
NamingEnumeration result = anonymousCtx.search(vBaseDN,
filter, ctls);
while (result.hasMore())
{
SearchResult sr = (SearchResult)result.next();
vUsrDN = sr.getName()+","+vBaseDN;
}
}
catch (Exception e)
{
System.out.println("Error from BindAnonymous - "+
e.getMessage());
}
/* returning User DN with Base DN */
return vUsrDN;
}