A knowledge base article about LDAP Code Samples provided by the UC Berkeley IT Service Hub - Knowledge Portal
Below are code samples for connecting to the LDAP directory in various languages:
This module is maintained by the IST Web Applications group. Once you install it, you can access either the ri documentation, or the html-based documentation by running gemserver on your host.
To follow referrals in PHP, you have to explicitly tell PHP that you want the LDAP server to return the referral to you. In PHP, the default is for the PHP LDAP library to tell the LDAP server not to follow referrals. In PHP, not only do you have to set the referral option, but you also have to explicitly set the LDAP v3 protocol. Below is an example of how to have PHP tell the LDAP server that referrals should be returned:
$ds = ldap_connect('ldap-test.berkeley.edu');ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);ldap_set_option($ds, LDAP_OPT_REFERRALS, 1); |
Please see the following reference for more information: ldap_set_option.
As with PHP, to follow referrals in Java, you have to explicitly tell Java that you want the LDAP server to return the referral to you. In Java, the default is for the Java LDAP library to tell the LDAP server not to follow referrals. Below is an example of how to have Java tell the LDAP server that referrals should be returned:
// Set the referral property to "follow" referrals automaticallyenv.put(Context.REFERRAL, "follow");// Create the initial contextDirContext ctx = new InitialDirContext(env); |
Please see the following references for more information: Referrals in the JNDI and Automatically Following Referrals.
As with PHP and Java, to follow referrals in .Net, you have to explicity tell .Net that you want the LDAP server to return the referral to you. In .Net, the default is for the .Net LDAP library to tell the LDAP server not to follow referrals. Below is an example of how to have .Net tell the LDAP server that referrals should be returned:
// Assume ldapID is a valid LdapDirectoryIdentifier objectldapConn = new LdapConnection(ldapID);ldapConn.SessionOptions.ProtocolVersion = 3;ldapConn.SessionOptions.ReferralChasing = ReferralChasingOptions.All; |
Thanks to Barry Waldman for providing this information for .Net.
Another more extended example is provided by Paul Hanson:
using (LdapConnection lConn = new LdapConnection(new LdapDirectoryIdentifier("ldap.berkeley.edu",389,false,false)))
{
lConn.AuthType = AuthType.Anonymous;
lConn.SessionOptions.ProtocolVersion = 3;
lConn.SessionOptions.ReferralChasing = ReferralChasingOptions.All;
SearchRequest _search = new SearchRequest();
_search.Filter = String.Format("(mail={0})", "pjhan@berkeley.edu");
_search.Scope = SearchScope.Subtree;
lConn.Bind();
var _sr = (SearchResponse)lConn.SendRequest(_search);
foreach (var item in _sr.Entries)
{
SearchResultEntry _sre = (SearchResultEntry)item;
Console.WriteLine(_sre.DistinguishedName);
}
Console.ReadKey();
}