I am trying to create a intranet website which can look up a users email address based on their Active Directory username.
I have the following in my web.config:
<authentication mode="Windows"/>
<identity impersonate="true"/>
And I can obtain the the users UserName with:
Environment.UserName
Running on localhost, the following code allows me to query the AD and obtain the email:
public string GetADUser(string userName)
{
DirectoryEntry entry = new DirectoryEntry();
// get a DirectorySearcher object
DirectorySearcher search = new DirectorySearcher(entry);
// specify the search filter
search.Filter = "(&(objectClass=user)(anr=" + userName + "))";
// specify which property values to return in the search
search.PropertiesToLoad.Add("mail"); // smtp mail address
// perform the search
SearchResult result = search.FindOne();
string email = string.Empty;
if (result != null)
{
if (result.Properties["mail"].Count == 1)
{
email = result.Properties["mail"][0].ToString();
}
else
{
email = "no email";
}
}
else
{
email = "not found";
}
return email;
}
Great, this code authenticates using my credentials by default and allows me to pass in a username and look up the users email address.
However, when I upload this test code to the server, the code stops working if I browse to the site from anywhere other than localhost.
[COMException (0x80072020): An operations error occurred.]
Googling this reveals that I have a permissions issue.
To get around this I have tried setting the application pool identity to my credentials but this still does not allow the code to search the AD.
The website authentication is configured in IIS as follows (enabled items tagged with <<):
Anonymous Authentication:Disabled
ASP.NET Impersonation:Enabled <<
Basic Authentication:Disabled
Digest Authentication:Disabled
Forms Authentication:Disabled
Windows Authentication:Enabled <<
Is it even possible to do what I am trying to do? What am I missing?
OK I found the problem.
In this case, having ASP.NET Impersonation:Enabled
in IIS and my Web.Config was conflicting with the Application Pool identity I had configured. (I think).
Once I set the application pool identity to run using an appropriate account authenticated to query the AD, disabled Impersonation and left Windows Authentication:Enabled
I was able to get the website to query the AD without passing any credentials in my code.
User contributions licensed under CC BY-SA 3.0