Active Directory Lookup from C# failing on server but works locally
At my workplace I have to deal with 2 different domains x.com (the parent directory) and it's subdomain y.x.com
The parent domain(x.com) has all the active directory users, computers etc. From my local workstation which sits in the x.com domain i can read emails for the active directory users just fine.
The server sits in domain y.x.com a sub domain of x. On the server the active directory read is failing and the email address is not being read from active directory.
In addition to this i tried to the same code from a virtual machine which sits in the y.x.com domain (same as the server) and to my surprise this worked.
I am using directory services in .NET to do this and my code is below:
string userEmail = string.Empty;
try
{
accountName = accountName.Replace(ConfigurationManager.AppSettings["DomainName"].ToString(), "");
DirectorySearcher ds = new DirectorySearcher()
{
SearchRoot = new DirectoryEntry()
{
Path = ConfigurationManager.AppSettings["DirectoryPath"].ToString(),开发者_JAVA技巧
AuthenticationType = AuthenticationTypes.Secure
}
};
ds.Filter = "(SAMAccountName=" + accountName + ")";
ds.PropertiesToLoad.Add(ConfigurationManager.AppSettings["ADMailPropertyName"].ToString());
SearchResult result = ds.FindOne();
if (result != null)
{
userEmail = result.Properties[ConfigurationManager.AppSettings["ADMailPropertyName"].ToString()][0].ToString();
}
}
catch (Exception e)
{
//Log error
}
return userEmail;
Any help would be appreciated.
Does the user-account that your program runs as on the server have the necessary permissions to Active Directory?
the server process is probably running under some local machine account (system, local). You probably need to supply proper credentials to this overload of the DirectoryEntry constructor.
The comment on Greg's answer states that you use 1) impersonation and 2) windows authentication. This means that your server knows who you are, and are impersonating you.
But... your server can not delegate those credentials to the remote server (the x.com domain server). This is a potential security breach which, if it was possible, allow a site to forward your credentials to any third party.
One solution is to use kerberos authentication and enable your server for delegation. I've never done this myself, so cant really help you out with the details.
You can read more about it at The Double-Hop Problem.
精彩评论