Chris Knight
Chris Knight

Reputation: 1476

ASP.NET MVC Active Directory code to retrieve all users stops working when deployed to IIS 7

I have an intranet ASP.NET MVC3 web application that is using Windows authentication with .NET Framework 4. All my code is working as far as authenticating the users. I am using Windows Authentication for the baseline authentication, and then link the Active Directory user to a user in a table in SQL Server 2008 for additional user properties specific to my application. All of that is working fine.

There is a section of the site where admins can select Active Directory users to add to the SQL user table (see above) and put in their site specific properties (IsAdmin, ShoeSize, etc.). On this screen, there is a drop down list that I populate to retrieve all Active Directory from a custom object I created that just holds the username and full name properties of the Active Directory user. Here is this code for that:

            public IQueryable<ActiveDirectoryUser> ActiveDirectoryUsers
            {
                get
                {
                    // get list of users in the Active Directory
                    DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.UserDomainName);
                    List<DirectoryEntry> activeDirectoryUsers = dirEntry.Children.Cast<DirectoryEntry>()
                        .Where(c => c.SchemaClassName == "User").ToList();

                    // populate a custom class I have to hold the active directory user's username and full name property values
                    return activeDirectoryUsers
                        .Where(u => !string.IsNullOrEmpty(u.Properties["FullName"].Value.ToString()))
                        .Select(u => new ActiveDirectoryUser()
                        {
                            NetworkId = String.Format(@"{0}\{1}", Environment.UserDomainName, u.Properties["Name"].Value),
                            FullName = u.Properties["FullName"].Value.ToString()
                        }).AsQueryable();
                }
            }

For some reason, this code returns no results when the web application is deployed to IIS 7. However, this works perfectly when running the site from IIS Express in Visual Studio. Any ideas of why this would be happening? I have been looking for IIS settings as the culprit, but have not found anything helpful. Do I need to change the way I am retrieving the Active Directory users? Thank you!

Upvotes: 1

Views: 2452

Answers (2)

Chris Knight
Chris Knight

Reputation: 1476

This issue ended up being a combination of Eric J. answer, and a change to my code for getting the Active Directory entries. I found that the DirectoryEntry method can be overloaded to take a username and password to use for the permissions (e.g. you don't have to rely on whatever account IIS is running under. Here is the code:

               List<SearchResult> searchResults;

                // use login account to access active directory (otherwise it will use the IIS user account, which does not have permissions)
                using (DirectoryEntry root = new DirectoryEntry("LDAP://CN=Users,DC=test,DC=example,DC=com", "usernameCredential", "passwordCredential"))
                using (DirectorySearcher searcher = new DirectorySearcher(root, "(&amp;(objectCategory=person)(objectClass=user))"))
                using (SearchResultCollection results = searcher.FindAll())
                {
                    searchResults = results.Cast<SearchResult>().ToList();
                }

                // get the active directory users name and username
                return searchResults
                    .Select(u => new ActiveDirectoryUser()
                    {
                        NetworkId = String.Format(@"{0}\{1}", this._domainName, u.Properties["sAMAccountName"][0]),
                        FullName = (string) u.Properties["cn"][0]
                    }).AsQueryable();

This allowed me to get the Active Directory entries, but only those are Users and person objects. Then I used LINQ to map it to my custom model.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150118

When running in IIS Express under Visual Studio you have a much higher permission set than running in the default security context of IIS 7.

You will have to understand exactly which permissions are needed to query Active Directory in this way and ensure that the application pool your app runs in under IIS 7 has that right. Be careful to grant only the permissions needed for this operation, and make sure you review the implications of granting those rights carefully before proceeding.

Upvotes: 1

Related Questions