Recently I faced with problem: we have 2 domains A and B with one way trust (domain A trusts domain B). Sharepoint installation belongs to domain A (Sharepoint system account is located in domain A). Users from domain B can login into Sharepoint site as domain A trusts domain B. Also we have code which makes some activities in AD:
- creates new user
- searches for users and groups
Code which creates and updates users and groups in AD successfully worked under account from trusted domain B (we use classes from System.DirectoryServices namespace). But search functionality failed with the following exception:
After investigation of problem I noticed that as DirectoryEntry class has possibility to specify credentials for accessing this entry (Username and Password properties) then there were no problems with creating and modifying as we explicitly specified credentials.
But for search we use DirectorySearcher class which has not such properties. Those entities which were returned by DirectorySearcher were binded using identity of current thread – and in the case when thread was impersonated by account of user from trusted domain B we had authentication error mentioned above.
Solution for this problem is to impersonate current thread with account which has access to AD of domain A on the moment when DirectoryEntry.Bind() is called. As I mentioned above in our environment Sharepoint system account belongs to domain A and it has access to its AD. So I used SPSecurity.RunWithElevatedPrivileges() for all these places where results of DirectorySearcher methods’ calls were used and after that error disappeared.
Notice that here SPSecurity.RunWithElevatedPrivileges() was used primarily for impersonation (i.e. I didn’t reopen SPSites and SPWebs under it). It simplified impersonation of current thread and allowed to avoid problems with re-impersonation on the initial account. If it is not suitable for you because of some reasons you can use WindowsIdentity.Impersonate() method for example.