Learn how LDAP and JNDI combine to form a powerful directory and Java object storage facility
- Feedback
- 13 Comments
(Note: To download this article's complete source code, see theResources section below.)
LDAP's basic structure is based on a simple information tree metaphor called a directory information tree (DIT). Each leaf in the tree is an entry; the first or top-level entry is the root entry. An entry includes a distinguished name (DN) and any number of attribute/value pairs. The DN, which is the name of an entry, must be unique. It shows the relationship between the entry and the rest of the DIT in a manner similar to the way in which a file's full path name shows its relationship with the rest of the files in a filesystem. While a path to a file reads left to right, a DN, in contrast, reads from right to left. Here is an example of an DN:
uid=styagi,ou=people,o=myserver.com
The leftmost part of the DN, called a relative distinguished name(RDN), is made up of an attribute/value pair. In the above example, this pair would be
uid=styagi
. LDAP attributes often use mnemonics, some examples of which are listed in Table 1.o | Organization |
ou | Organizational unit |
cn | Common name |
sn | Surname |
givenname | First name |
uid | Userid |
dn | Distinguished name |
mail | Email address |
Information about attributes, attribute matching rules, and relationships between objectclasses are defined in the server'sschema. Any attribute can have one or more values, depending on how it is defined the schema. A user, for example, can have more than one email address. There is also a special attribute called anobjectclass that specifies the required and allowed attributes for a particular entry. Like objects in Java, objectclasses in LDAP can be extended to retain existing attributes and add new ones.
A naming service associates names with objects and finds objects based on their given names. (The RMI registry is a good example of a naming service.) Many naming services are extended with adirectory service. While a naming service allows a lookup of an object based on its name, a directory service also allows such objects to have attributes. As a result, with a directory service we can look up an object's attributes or search for objects based on their attributes.
So where does JNDI fit into this LDAP jargon? JNDI does for LDAP what JDBC does for Oracle -- it provides a standard API for interacting with naming and directory services using a service provider interface (SPI), which is analogous to an JDBC driver. LDAP is a standard way to provide access to directory information. JNDI gives Java applications and objects a powerful and transparent interface to access directory services like LDAP. Table 2 below outlines common LDAP operations and their JNDI equivalents. (For a detailed look at the JNDI specification, seeResources.)
Operation | What it does | JNDI equivalent |
Search | Search directory for matching directory entries | DirContext.search() |
Compare | Compare directory entry to a set of attributes | DirContext.search() |
Add | Add a new directory entry | DirContext.bind() ,DirContext.createSubcontext() |
Modify | Modify a particular directory entry | DirContext.modifyAttributes() |
Delete | Delete a particular directory entry | Context.unbind() , Context.destroySubcontext() |
Rename | Rename or modify the DN | Context.rename() |
Bind | Start a session with an LDAP server | new InitialDirContext() |
Unbind | End a session with an LDAP server | Context.close() |
Abandon | Abandon an operation previously sent to the server | Context.close() , NamingEnumneration.close() |
Extended | Extended operations command | LdapContext.extendedOperation() |
Manipulate objects in the LDAP server
Let's cut to the chase and see how to manipulate objects in the LDAP server. The standard LDAP operations include:
- Connect to the server
- Bind to the server (think of this as authentication)
- Add new entries in the LDAP server
- Modify an entry
- Delete an entry
- Search the server for an entry
We'll examine each of these steps in the sections below, with examples.
Before executing the examples, you will need to install the LDAP server, the JNDI classes, and (unless you want to disable schema checking) the Java schema. You can find install information in the JNDI zip file's schema directory. Our examples use Netscape Directory Server 4.1 and JDK 2. (To install these packages, see Resources.)
Connect to the server
To connect to the server, you must obtain a reference to an object that implements the
DirContext
interface. In most applications, this is done by using an InitialDirContext
object that takes a Hashtable
as an argument. The Hashtable
contains various entries, such as the hostname, port, and JNDI service provider classes to use:Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389"); DirContext ctx = new InitialDirContext(env);
Bind to the Server
Once connected, the client may need to authenticate itself; this process is also known as binding to the server. (Be aware that the word binding can also refer to the act of adding something to the directory.)
In LDAP version 2, all clients had to authenticate while connecting, but version 3 defaults to anonymous and, if the default values are used, the connections are anonymous as well. LDAP servers maintain rights using access control lists (ACLs) that determine what particular access is available to an entry by an application. LDAP supports three different security types:
- Simple: Authenticates fast using plain text usernames and passwords.
- SSL: Authenticates with SSL encryption over the network.
- SASL: Uses MD5/Kerberos mechanisms. SASL is a simple authentication and security layer-based scheme
The client authenticates itself to the server by specifying values for different environment variables in the
Context
interface, as seen below:Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389"); env.put(Context.SECURITY_AUTHENTICATION,"simple"); env.put(Context.SECURITY_PRINCIPAL,"cn=Directory Manager"); // specify the username env.put(Context.SECURITY_CREDENTIALS,"password"); // specify the password DirContext ctx = new InitialDirContext(env);
Add new entries in the LDAP server: The options
The LDAP directory server can act as a repository for Java objects. JNDI provides an object-oriented view of this directory, which means that Java objects can be added to and retrieved from the directory without the client needing to manage data representation issues.
Objects can be stored in three ways:
- Store the Java objects themselves
- Store a reference to the object
- Store information as attributes
Let's take a look at each of these in more detail.
Store the Java objects themselves
If a class implements the
java.io.Serializable
interface, it can be serialized and deserialized from storage media. If we need a simple name-object binding (as in the RMI registry), then theContext.bind()
method can store the object. But if we need the more powerful technique of associating attributes with the stored object, we'd employ the DirConext.bind()
method instead. Whichever method we use, the object's state is serialized and stored in the server:MyObject obj = new MyObject(); ctx.bind("cn=anobject", obj);
Once stored, we can retrieve the object by looking up its name in the directory:
MyObject obj = (MyObject)ctx.lookup("cn=anobject");
When an application serializes an object by writing it to an object stream, it records information that identifies the object's class in the serialized stream. However, the class's definition, which is contained in the classfile, is not itself recorded. The system that deserializes the object is responsible for determining how to locate and load the necessary class files.
Alternatively, the application can record the codebase with the serialized object in the directory, either when the binding occurs or by subsequently adding an attribute using
DirContext.modifyAttributes()
. (We'll examine this second technique later in this article.) Any attribute can record the codebase as long as the application reading back the object is aware of the attribute name. As another option, we can employ the attribute "javaCodebase"
specified in the LDAP schema for storing Java objects if schema checking is enabled on the server.
The above example can be modified to supply a codebase attribute containing the location of the
MyObject
class definition:// Create object to be bound MyObject obj = new MyObject(); // Perform bind and specify codebase BasicAttribytes battr = new BasicAttributes("javaCodebase","http://myserver.com/classes") ctx.bind("cn=anobject", obj, battr)
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public class LdapSearch { public static void main(String[] args) throws Exception { Hashtable env = new Hashtable(); String sp = "com.sun.jndi.ldap.LdapCtxFactory"; env.put(Context.INITIAL_CONTEXT_FACTORY, sp); String ldapUrl = "ldap://localhost:389/dc=yourName, dc=com"; env.put(Context.PROVIDER_URL, ldapUrl); DirContext dctx = new InitialDirContext(env); String base = "ou=People"; SearchControls sc = new SearchControls(); String[] attributeFilter = { "cn", "mail" }; sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(&(sn=W*)(l=Criteria*))"; NamingEnumeration results = dctx.search(base, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); Attribute attr = attrs.get("cn"); System.out.print(attr.get() + ": "); attr = attrs.get("mail"); System.out.println(attr.get()); } dctx.close(); } }
Hello ,
ReplyDeleteReally it's good
I understand here JNDI does for LDAP what JDBC does for Oracle(DataBase.)
JNDI give tha facility to Java application and object to implenets the INTERFACE WHICH US REQUIRED for LDAP access
ReplyDelete1. Make a LDAP Connection.
2. Bind with the Server
3. Does the activity as required
Basic Operation :
1. DirContext.Search(); DirContext.search();
2. DirContext.Compare(); //
3. DirContext.Add(); // DirContext.bind();
4. Modify // DirContext.modifyAttribut();
5. Delete // DirContext.unbind();
6. Rename // DirContext.rename();
Code for JAVA (JNDI and LDAP)
Hashtable env = new Hashtable();
env.put(context.INITIAL_CONTEXT_FACTORY,"com.sun.ldap.LdapCtxFactory");
env.put(context.PROVIDER_URL,"ldap://localhost:8080");
env.put(context.SECURITY_AUTHORISATION,"sample");
env.put(context.SECURITY_PROVISION,"cn=MyDirectory Server");
env.put(context.SECURITY_CREDENTIAL,"pass");
DirContext ctx = new InitialDirContext(env);
===================================================================
Harrah's Ak-Chin Casino Resort - Kmart
ReplyDeleteHarrah's Ak-Chin Casino Resort. 777 Casino Dr. Joliet, IL 60401-7611. Phone: *** 의왕 출장마사지 **** *** ext: **** ext: **** ext: **** *** ext: **** ext: **** ext: **** ext: **** ext: *** ext: **** 전주 출장샵 ext: *** 화성 출장안마 ext: **** ext: **** 속초 출장마사지 ext: **** ext: *** ext: **** ext: **** ext: **** ext: ** ext: **** ext: *** 인천광역 출장샵 ext: