Tag Archives: RegEx

RegEx for LDAP

I have been working on a POC for injecting bulk entitlements into our Access Management System.  I guess you could think of our system as a big loop.  Entitlements are created in the AMS.  Users request an entitlement, which kicks off a workflow.  Once the entitlement is approved, it flows into AD.  The part I have been noodling around with is reading the permission out of AD.

I’ve been playing with this for years, literally.  I wrote some simple code a few years back.  For this POC, I dusted it off and showed it around.  I still had to migrate the code into the POC solution, so I had a chance to clean it up a bit.  No problem.  My old code uses UserPrincipals to pull the data out of AD.

var ctx = new PrincipalContext(ContextType.Domain);

var userPrincipal = await Task<UserPrincipal>.Factory.StartNew(() => UserPrincipal.FindByIdentity(ctx, request.UserId)) ?? new UserPrincipal(ctx);
response.User = userPrincipal.Convert();

It can be a bit slow.  At least the first query is slow.  It gets faster after the spin up.  Still…  I think I can make it better.

After poking around for a bit, I found the information I needed to access the AD container via LDAP.  Amazingly enough, the security team posted all of the needed info on the internal Wiki.  I’m not going to go into too much detail because I don’t really want to share any details about our network.

Anyway, once I pulled the data, I needed to parse the data into something I could use for my POC.  I looked around online and I could not find a single reference that showed a complete RegEx sample.  I saw some fragments, but nothing complete.  So here is what I came up with…

var regex = new Regex($@”CN=(?<CN>[\w]+)(,OU=(?<OU>\w+( \w+)*))+(,DC=(?<DC>\w+))+);

That’s it.  I only need the “CN” portion of the string but I thought I’d parse everything for future use.

Enjoy.

PS: I’ll fix the broken images when I have a chance.