This weekend I was working on a reverse proxy for the EWS protocol. Someone might find the code useful when Basic Authentication is shut down for good on Office365 tenants.
Part of the code queries email addresses in Active Directory. Seems like a simple operation, right? Well, my first approach was using the ldap3 Python library. It's well-tested, simple, and supposed to work.
However, I didn't really like that I would actually have to discover the LDAP server myself. That, or have the server endpoint, authentication, and query search base set manually. What sort of end-user even knows how to do that? Applications should be able to just magically do that on their own, right? Use the system login or whatever?
Doing that with the ldap3 package seemed like quite the hassle, involving other packages to look up SRV records or what have you and then managing to authenticate on top of that. Honestly, we could use a library that adds a bit more magic to querying Active Directory.
Is there a simpler way? Much simpler, so long as it fits the purpose (and you're on Windows). PowerShell saves the day. All you need to do for configuration-less queries is just installing the RSAT tools and then using PowerShell to run queries with Get-ADUser. It can run LDAP queries directly.
Here's a quick example, fetching the "targetAddress" from a user's email address:
powershell_command = (f"(Get-ADUser -Properties targetAddress -LDAPFilter "
f"'(&(objectClass=user)(objectCategory=person)"
f"(|(mail={email})(proxyAddresses=SMTP:{email}))"
f"(!(cn=SystemMailbox{{{{*)))').targetAddress")
targetAddress = subprocess.check_output(
f"powershell \"{powershell_command}\"".strip(),
shell=True ).decode("utf-8").strip()
It's a bit hacks, I say, but it works and it's easy. I just wish I could format that query string better. I sadly found that Get-ADUser doesn't like any extra whitespace in the query string.