Laureano Bonilla
Laureano Bonilla

Reputation: 335

DirectorySearcher object data retrieving not working on Azure hosted application

This code used to work for me in order to retrieve the AD information of a user when passing ID by parameter.

    public UsersDTO GetUserFromActiveDirectoryByID(string userID)
    {
        DirectorySearcher ds = new DirectorySearcher();            
        ds.Filter = "(&(objectClass=user)(objectcategory=person)(name=" + userID + "))";
        SearchResultCollection results = ds.FindAll();
        SearchResult userProperty = results[0];    
        UsersDTO user = new UsersDTO();
        if (userProperty.Properties["mail"].Count > 0)
        {                
            user.fullName = userProperty.Properties["displayname"][0].ToString();                
            user.email = userProperty.Properties["mail"][0].ToString();             
        }
        return user;
    }

It worked while the application service was hosted in another server, but now that it has been migrated to Azure, the FindAll command (also FindOne was tested) returns "There was an error retrieving the data.","Status":400,"Detail":"Access is denied."

Upvotes: 0

Views: 218

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 41008

You aren't setting the SearchRoot of your DirectorySearcher. The documentation for SearchRoot says:

If SearchRoot is a null reference (Nothing in Visual Basic), the search root is set to the root of the domain that your server is currently using.

If the other server was joined to the domain that you are trying to search, then that's why it was working. But that is no longer true when you're on Azure.

So you need to specify the SearchRoot to point it at your domain:

DirectorySearcher ds = new DirectorySearcher();
ds.SearchRoot = new DirectoryEntry("LDAP://example.com");

This may also introduce issue of whether you can actually access your domain controllers from Azure. You may need to open firewall rules to allow it, depending on how your environment is setup.

Upvotes: 0

Related Questions