Encapsulate a LDAP DN string using Arrays in PHP

Tags

During a project I had to fork privileges assignation logic with information coming from an LDAP server. Since the DN string representing users can be very different for each user: their affiliations and roles. I had to find ways to interpret sub-parts of that string to figure out what privileges to attach to them.

My snippet's purpose is to get the capability to get a subset of that LDAP DN string, assuming that the first index is more precise than the last, but concatenated would give the full context.

While I was trying to find already made function that explodes that string into manageable arrays in PHP, I realized that there was none. I then decided to contribute it as a comment on the PHP.net website.

 

­

The basics

As a reminder, an LDAP DN string looks like the following:
  CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com

In such a string, we get basically everything a user may inherit from:

  • Group assignation
  • Organization domain (either DNS or Microsoft's idea of a "domain" (aka. "Active Directory"))
  • etc.

The main idea is to deal with different logic based on changes or assignment. The DN has all we need.

Reading the data from it can be done using successive explode on the = and the ,. But How about to use the implicit hierarchy the string conveys.

My objective was to read the previously shown DN string, and parse a manageable array that would look like this:`

    array(
        'CN' => array("username"),
        'OU' => array("UNITNAME","Region","Country"),
        'DC' => array ("subdomain","domain","com")
    );

 

­

How to use

Assuming we want to work with changes in the OU field. We could do as:
find($userId); // $user instanceof User

// This is coming from the LDAP
$dn= 'CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com';

$wrapper = parseLdapDn($dn);
// We are working with "UNITNAME" but there can be other ones
switch($wrapper['OU'][0]){
    case 'UNITNAME':
        // Specific logic or authorization setters
        $user->addRole('ROLE_UNITNAME');
    break;

    default:
      // Default behavior, in case we did not grasp
    break;
}

// And so on...

In this example I added a role using Symfony2's method on a Doctrine2 provided object. But you may see other use cases.

 

­

Snippet

I also published it as a comment on the PHP.net website.

 

­

That is all folks

If you have other questions or suggestions, let me know.