How to start with C# Async and Await Working remotely as a Freelancer



Get user certificate from Active Directory

Recently I was working with Exchange Web Services or EWS. It’s a neat way to communicate with Exchange Server and manage it’s data, emails in particular. You can do a lot with it, but my task was to encrypt email messages by pooling a recipient certificate from Active Directory, save it to Exchange server and send it to the recipient. Long story short, this is not a post about EWS, but here I will show you a method that will return X509Certificate2 object back from a byte array, stored under userCertificate property in Active Directory.

In order to work with Active directory, you will need to import System.DirectoryServices to your project.

Add Directory Services reference

The GetUserCertificateFromAD is not a “production grade” method, but it’s a good start. It is somewhat flexible; you can set username and password to authenticate to Active Directory or you can just set it to null. Second, you set the name of the property you want to fetch from AD and finally you can pass the LDAP filter. The property in my case was userCertificate and the filter was (&(objectCategory = person)(objectClass = user)(name={0})). Please note, that function only returns first certificate from the array:

After that it creates a certificate from that array and returns it.

GetUserCertificateFromAD method

Use it like this:

If you want to filter out users by e-mail address use this filter below. Just replace (name={0}) with (mail={0}) and pass in the email address and you are good to go.

Ta-da!

About Miha
I've always been fascinated by computers. I am happy that I can work in this creative field of software development, where I can solve problems. I am also an avid cyclist :) and I love to learn...a lot!
Related Posts
  • All
  • By Author
  • By Category
  • By Tag

Leave a Reply