Search code examples
.netserviceactive-directoryaccount

Required access rights and potential side effects when querying Active Directory via .NET


I have written the following code to check whether a domain user is enabled and exists within our Active Directory. What I am wondering about as I am new to AD querying: What rights in terms of access rights for the AD do I need to query the AD? This code runs fine when run under my account, but I would like to run it as service and am wondering about the necessary access rights for the service account?

Also, could there be any side effects in the AD when sending these queries? I don't think I would be able to lock the queried accounts with this code, but I am rather careful so wanted to ask the question here.

PrincipalContext context = new PrincipalContext(ContextType.Domain);
foreach (String x in new String[] { "mydomain\blub", "mydomain\blab", "mydomain\blib" })
{
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, x);

    if (user == null || user.Enabled == false)
        Console.WriteLine(x + " --> Account kaputt!");
    else
        Console.WriteLine(x + " --> Account enabled!");
}

Solution

  • By default you do not need any extra permissions to query user account from Active Directory. If account used by your app is common Active Directory account or app is configured to use NetworkService account (https://msdn.microsoft.com/en-us/library/windows/desktop/ms684272(v=vs.85).aspx) on computer joined to Active Directory domain, it will just work.

    Basic considerations for accessing Active Directory this way is performance and security. So you should make sure you do not overload your environments with (unnecessary) queries and make sure you access Active Directory in a safe way.

    Also consider using PowerShell for simple tasks like this - you can achieve similar by running

    @('blub', 'blab', 'blib') | Get-ADUser | select Name, Enabled
    

    and there is no need to compile this