Question: Is it possible to determine whether an account is a service account in Active Directory using C# LDAP? If yes, how?
Context: I have a program that is retrieving all objects of schema class type USER, GROUP, COMPUTER, FOREIGN SECURITY PRINCIPAL, and CONTACT. Currently, a service account is identified by string parsing the canonical name for 'service account'. I do not like this solution because string parsing is dependent on a folder location in the hierarchy that literally says 'service account'. It seems possible that a service account could be created and then placed in a folder path that does not include the string 'service account'. Unfortunately, I cannot test this because I am not an AD admin.
I have browsed around online without any luck so I am not sure if it is even possible.
Update:
Per Microsoft, it appears that the service account is contained in objectClass msDS-ManagedServiceAccount. However, when I set the DirectoryEntry filter to msDS-ManagedServiceAccount, no results are returned.
directoryEntry = new DirectoryEntry(strActiveDirectoryHost, null, null, AuthenticationTypes.Secure);
string strDsFilter = "(objectClass=msDS-ManagedServiceAccount)";
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry)
{
Filter = strDsFilter,
SearchScope = SearchScope.Subtree,
PageSize = intActiveDirectoryPageSize,
};
return searchResultCollection = directorySearcher.FindAll();
So I am working on this to get the MSA as well as create them. I am able to get the MSA using the System.DirectoryServices.AccountManagement namespace, still working on creating it (unsure if this is really possible) But for finding the accounts which are MSAs you can use the below code
You can use the above logic and create a Principal for the user account and get the structural object class for that account to find out if it is MSA. Something like this:
I have testing your code, and it does in fact return results in my environment. A few things to note:
strActiveDirectoryHost
is formatted correctly. The format should beLDAP://DC=contoso,DC=com
Managed Service Accounts
container under the domain NC (i.e.LDAP://CN=Managed Service Accounts,DC=contoso,DC=com
)new DirectoryEntry()
with only the path. Not sure if passingAuthenticationTypes.Secure
is causing an issue for you