简体   繁体   中英

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."

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM