cogSnippet to make LDAP queries from XWiki
TypeSnippet
CategoryOther
Developed by

Ludovic Dubost

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Description

This snippet allows to run LDAP queries on any LDAP directory (including the one configured for XWiki):

{{groovy}}
import org.xwiki.velocity.tools.EscapeTool;
import org.xwiki.contrib.ldap.XWikiLDAPConfig;
import org.xwiki.contrib.ldap.XWikiLDAPConnection;
import org.xwiki.contrib.ldap.XWikiLDAPSearchAttribute;
import com.novell.ldap.LDAPConnection;

def escapetool = new EscapeTool();

def getConfig(param) {
 return xwiki.getXWiki().getXWikiPreference(param, "xwiki.authentication." + param.replaceAll("ldap_", "ldap."),
                                            "", xcontext.getContext());
}

def getParamFromConfig(name) {
  return getParamFromConfig(name, "ldap_" + name);
}

def getParamFromConfig(name, ldapname) {
 if (request.getParameter(name)!=null) {
   return request.getParameter(name)
 } else {
   return getConfig(ldapname);
 }
}

def getParam(name, defaultvalue) {
 if (request.getParameter(name)!=null) {
   return request.getParameter(name)
 } else {
   return defaultvalue;
 }
}

def getTrustedLDAPConfig() {
 def map = new HashMap();
 for (paramname in ["server", "port", "base_DN", "bind_DN", "bind_pass"]) {
  def param = xwiki.getXWiki().Param("xwiki.authentication.trustedldap.remoteUserMapping.ldap_" + paramname);
  if (param==null)
   continue;
  try {
   for (config in param.split("\\|")) {
     def pos = config.indexOf("=");
     domain = config.substring(0, pos);
     domainparam = config.substring(pos + 1);
     def domainmap = map.get(domain);
     if (domainmap==null) {
       domainmap = new HashMap();
       map.put(domain, domainmap);
     }
     domainmap.put(paramname, domainparam);
   }
  } catch (e) {
    println "Failed reading param ${param}: " + e.getMessage();
  }
 }
 return map;
}

def map = getTrustedLDAPConfig();
if (map.size()>0) {
 print "Use config: "
 for (key in map.keySet()) {
   print """[[${key}>>||queryString="domain=${key}"]] """
 }
 println ""
 println ""
}

if (request.domain) {
 server = map.get(request.domain).get("server");
 port = map.get(request.domain).get("port");
 binddn = map.get(request.domain).get("bind_DN");
 bindpassword = map.get(request.domain).get("bind_pass");
 basedn = map.get(request.domain).get("base_DN");
} else {
 server = getParamFromConfig("server")
 port = getParamFromConfig("port")
 binddn = getParamFromConfig("binddn", "ldap_bind_DN")
 bindpassword = getParamFromConfig("bindpassword", "ldap_bind_pass")
 basedn = getParamFromConfig("basedn", "ldap_base_DN")
}


if (port==null || port=="") port = "389"
query = getParam("query", "sn=ldubost")
params = getParam("params", "dn,samAccountName")

println """
{{html clean="false"}}
<form action="" method="GET">
<table>
<tr><td>Server</td><td><input type="text" name="server" value="${escapetool.xml(server)}" size="20" /></td></tr>
<tr><td>Port</td><td><input type="text" name="port" value="${escapetool.xml(port)}" size="20" /></td></tr>
<tr><td>Bind DN</td><td><input type="text" name="binddn" value="${escapetool.xml(binddn)}" size="80" /></td></tr>
<tr><td>Bind Password</td><td><input type="password" name="bindpassword" value="${escapetool.xml(bindpassword)}" size="20" /></td></tr>
<tr><td>Base DN</td><td><input type="text" name="basedn" value="${escapetool.xml(basedn)}" size="80" /></td></tr>
<tr><td>LDAP Query</td><td><input type="text" name="query" value="${escapetool.xml(query)}" size="80"/></td></tr>
<tr><td>Params</td><td><input type="text" name="params" value="${escapetool.xml(params)}" size="80"/></td></tr>
</table>

<input type="submit" value="Go" class="button" />
</form>
{{/html}}
"""

def connection = new LDAPConnection();

try {
  // connect
  connection.connect(server, Integer.parseInt(port))
  connection.bind(LDAPConnection.LDAP_V3, binddn, bindpassword.getBytes("UTF8"));
  def paramslist = null;
  if (params!="") {
   paramslist = params.split(",")
  }
  def results = connection.search(basedn, (int) 2, query, paramslist, false);
  while (results.hasMore()) {
   try {
    def entry = results.next()
    def dn = entry.getDN()
    println "* ${dn}"
    def attrs = entry.getAttributeSet()
    for (attr in attrs) {
     try {
      println "** ${attr.getName()} ${attr.getStringValue()}"

      if (attr.getName()=="member") {
        for (item in attr.getStringValueArray()) {
          println "*** ${item}"
        }
      }

     } catch(e2) {
      println "** Exception getting attribute"
     }
    }
    } catch(e3) {
      println "** Exception calling next"+e3
    }
  }
} catch (e) {
   e.printStackTrace();
   println("Exception")
   println(e.getMessage())
   println(org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(e));
}

{{/groovy}}

Older version of this code:

Tool to find information in LDAP Directory:


* Find a user:  
** cn=Ludovic Dubost
** cn=Dubost
* Find groups of user:
** member=CN=Ludovic DUBOST,O=xwiki.com

{{groovy}}
import org.xwiki.velocity.tools.EscapeTool;
import org.xwiki.contrib.ldap.XWikiLDAPConfig;
import org.xwiki.contrib.ldap.XWikiLDAPConnection;
import org.xwiki.contrib.ldap.XWikiLDAPSearchAttribute;
import com.novell.ldap.LDAPConnection;

def escapetool = new EscapeTool();
def server = "";
def binddn = "";
def bindpassword = "";
def query = "";

if (request.server) {
  server = request.server;
} else {
  server = xwiki.getXWikiPreference("ldap_server", "");
}
if (request.binddn) {
  binddn = request.binddn;
} else {
  binddn = xwiki.getXWikiPreference("ldap_bind_DN", "");
}
if (request.bindpassword) {
  bindpassword = request.bindpassword;
} else {
  bindpassword = xwiki.getXWikiPreference("ldap_bind_pass", "");
}
if (request.basedn) {
  basedn = request.basedn;
} else {
  basedn = xwiki.getXWikiPreference("ldap_base_DN", "");
}
if (request.query) {
  query = request.query;
} else {
  query = "cn=Ludovic Dubost";
}
println "Server: ${server}"

def squery = escapetool.xml(query)
def sserver = escapetool.xml(server)
def sbinddn = escapetool.xml(binddn)
def sbindpassword = escapetool.xml(bindpassword)
def sbasedn = escapetool.xml(basedn)

println """
{{html clean="false"}}
<form action="" method="POST">
Server: <input type="text" name="server" value="$sserver" size="20" /><br />
Bind DN: <input type="text" name="binddn" value="$sbinddn" size="80" /><br />
Bind Password: <input type="password" name="bindpassword" value="$sbindpassword" size="20" /><br />
Base DN: <input type="text" name="basedn" value="$sbasedn" size="80" /><br />
LDAP Query: <input type="text" name="query" value="$squery" size="80"/><br />

<input type="submit" value="Go" />
</form>
{{/html}}
"""


def connection = new LDAPConnection();

try {
 // connect
  connection.connect(server, 389)
  connection.bind(LDAPConnection.LDAP_V3, binddn, bindpassword.getBytes("UTF8"));
  String[] params = new String[2]
  params[0] = "dn"
  params[1] = "samAccountName"

 def results = connection.search(basedn, (int) 2, query, params, false);
 def count= results.getCount()
  println "${count} results"
 while (results.hasMore()) {
  try {
   def entry = results.next()
   def dn = entry.getDN()
    println "* ${dn}"
   def attrs = entry.getAttributeSet()
   for (attr in attrs) {
    try {
      println "** ${attr.getName()} ${attr.getStringValue()}"
     } catch(e2) {
      println "** Exception getting attribute"
     }
    }
    } catch(e3) {
      println "** Exception calling next"
    }
  }
} catch (e) {
   e.printStackTrace();
   println("Exception")
   println(e.getMessage())
   println(org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(e));
}

{{/groovy}}

Prerequisites & Installation Instructions

Copy-paste the code in your wiki

Tags: ldap
     

Get Connected