There will be times when using the Active Directory Membership to provide authentication to a web application is just not feasible. But the requirement can still be to match an Active Directory user to an entry at the application’s database. Thankfully Microsoft has provided developers with a good abstraction to access Active Directory (System.DirectoryServices). As part of my research I decided to create a small console application that will communicate with Active Directory, get a list of all users belonging to a specific group, be able to get all properties (like displayName, physicalDeliveryOfficeName, homeDirectory, countryCode, sAMAccountName, etc.) from the user’s Active Directory entry and specifically convert the objectsid (byte[] array) to a string representing the SID.
The namespace System.DirectoryServices provides access to Active Directory Domain Services and allows you to connect to Active Directory and search for objects within this special database.
DirectoryEntry represents an object in the Active Directory Domain Services tree hierarchy. By connecting you establish the returned object as your root for next searches. For this connection to happen you need to provide the path (in my case was the standard LDAP path, example: “LDAP://mydomainAD.net“) and your security credentials. Is best to ask your local AD Admin to setup an account for this application.
Next we need to perform a search and get our results:
Another call to DirectoryEntry but passing each member’s information returns the AD properties for such user and allows me to query each of its properties like (sAMAccountName, name, homeDirectory, etc.)
I am interested in one particular property, the user’s “objectSid“. Once I have the value (byte[]) I pass it to another method to transform it to a security token (SID).
I used a SecurityIdentifier to transform the byte[] to a meaningful SID token. All happening within Windows’ own methods.
The resulting value (SID formatted) is: “S-1-5-21-1348824495-855021684-617735142-29890”
You can download this code sample: PublishADProperties.cs