2006
08.15

LDAP From a CGI

When I’m writing web code these days, I find myself using LDAP in some form almost every time. It’s become the “glue” that ties a lot of our web/intranet apps together. If you have never worked with LDAP from within a CGI, here is a kind of skeleton example to get you started. It uses perl’s Net::LDAP module to grab a list of users from the “Domain Users” OU of our Active Directory and show them in an HTML table. The returned results are sorted alphabetically by first name (“givenName” in directory speak). Net::LDAP is feature rich and has all the bells and whistles you are likely to need for an intranet app. Check out the API documentation for more details.

#!/usr/bin/perl -w
use Net::LDAP;
use strict;

##: Bind anonymously to the ldap database
my $basedn="ou=Domain Users,dc=domain,dc=com";
my $ldap=Net::LDAP->new(’ldap.domain.com’) 
  or die "Couldn’t connect to directory server.\n";
my $mesg=$ldap->bind(’user@domain.com’,password=>’********’) 
  or die "Couldn’t bind to directory server.\n";

##: Query LDAP to get a list of users and their info
$mesg=$ldap->search( 
  base=> $basedn,
  filter=> "(objectClass=user)",
  attrs=> [’displayName’,’givenName’,
           ’sn’,’mail’,’telephoneNumber’,
           ’streetAddress’,’l’,’st’,
           ’postalCode’,’homePhone’ ] );

##: Display the directory
my $count=0;
my $results="";
foreach my $entry ($mesg->sorted(’givenName’)) {
  $results.="<tr>";
  $results.="<td>".$entry->get_value(&#8217;displayName&#8217;)."</td>";
  $results.="<td>".$entry->get_value(&#8217;streetAddress&#8217;)."</td>";
  $results.="<td>".$entry->get_value(&#8217;l&#8217;)."</td>";
  $results.="<td>".$entry->get_value(&#8217;st&#8217;)."</td>";
  $results.="<td>".$entry->get_value(&#8217;postalCode&#8217;)."</td>";
  $results.="<td>".$entry->get_value(&#8217;homePhone&#8217;)."</td>";
  $results.="<td>".$entry->get_value(&#8217;mail&#8217;)."</td>";
  $results.="</tr>";
  $count++;
}
$mesg=$ldap->unbind;

print STDOUT "Content-Type: text/html\n\n";
print STDOUT "<html>\n\n<head>\n";
print STDOUT "<title>User Listing - Full</title>\n";
print STDOUT "</head>\n\n<body>\n";
print STDOUT "Records Returned: <b>$count</b><br />\n";
print STDOUT "<table border=&#8217;1&#8217; rules=&#8217;1&#8217;><tr>";
print STDOUT "<th>Name</th>";
print STDOUT "<th>Address</th>";
print STDOUT "<th>City</th>";
print STDOUT "<th>State</th>";
print STDOUT "<th>Zip</th>";
print STDOUT "<th>Phone</th>";
print STDOUT "<th>Email</th>";
print STDOUT "</tr>\n";
print STDOUT $results;
print STDOUT "</table>\n";
print STDOUT "</body>\n</html>";

Switch to our mobile site