Ajax style LDAP access

Json2Ldap iconAjax-style directory access is easy with Json2Ldap.

What you need:

  1. A Json2Ldap installation to take in directory requests in the form of JSON messages and translate them to the binary LDAP protocol (and then back).
  2. An LDAP v3 compatible directory server, such as OpenLDAP, Microsoft Active Directory, IBM Tivoli Directory Server or Novell eDirectory.
  3. A JavaScript library to streamline the dispatch of XMLHttpRequests, my favourite is jQuery. Also a JSON encoder/decoder.

To utilise a remote directory you must connect to it first. Instead of devising its own message schema, Json2Ldap speaks standard JSON-RPC 2.0. Here is how the connect request is composed in JavaScript:

var request = {};
request.method = "ldap.connect";
request.params = {};
request.params.host = "ldap.host.net";
request.params.port = 389;
request.id = 0;
request.jsonrpc = "2.0";

The host and port parameters specify the network location of the LDAP server. Serialised to JSON the request may look like that:

 "method" : "ldap.connect",
 "params" : { "host" : "ldap.host.net", "port" : 389 },
 "id" : 0,
 "jsonrpc" : "2.0"

We then send off the request using jQuery’s HTTP POST wrapper. If all goes well the callback function will receive a result that contains an LDAP connection identifier, which we must save for later requests.

// The Json2Ldap URL
var url = "http://tomcat.host.net:8080/json2ldap/";

// The LDAP connection CID
var cid = null;

// The callback function
function saveCID(response) {
	if (response.result)
		cid = response.result;
	else if (response.error)
		alert("Connect error: " + response.error.message);

$.post(url, JSON.stringify(request), saveCID, "json");

Json2Ldap’s web API covers the entire set of standard LDAP commands as well as a few extended controls and operations. Search is however perhaps the most commonly used directory command.

function displaySearchResult(response) {	
	if (response.result)
		alert("Found " + response.result.matches.length + "match(es)");		
	else if (response.error)
		alert("Search error: " + response.error.message);

var request = {};
request.method = "ldap.search";
request.params = {};
request.params.CID = cid;
request.params.baseDN = "ou=people,dc=example,dc=com";
request.params.scope = "ONE";
request.params.filter = "(givenName=Agnese)";
request.id = 1;
request.jsonrpc = "2.0";

$.post(url, JSON.stringify(request), displaySearchResult, "json");

Here is an example search result entry, formatted as LDIF (users have got choice – Json2Ldap allows for JSON as well as LDIF result formatting).

Sample search result entry in LDIF format

In one of my next posts I’ll give you some cool mashup examples utilising the Json2Ldap web service 🙂