Impersonation for ASP.NET pages hosted in SharePoint
We do most our SharePoint development based on ASP.NET WebForms and UserControls. WebParts are only used to host UserControls and pass information between them using Connections. WebForms are frequently used as PopUp windows triggered by the UserControls.
In some scenarios you will want to set a different user account authentication for the popupwindows. SharePoint uses default Windows Authentication In our case we needed to have extended permissions to enable a popupwindow to display users from Active Directory using the DirectoryEntry and DirectorySearcher objects in System.DirectoryServices namespace. For regular ASP.NET applications this is usually trivial, and we made it work fairly quick when only running the ASPX'es from the vdir and not in SharePoint context.
The problem is related to the "double-hop" issue described in detail (with more links) by nuno here. We tried out the suggestions made by this Microsoft KB HOWTO. We configured IIS to use a authorized user for the pages that needed to access DirectoryServices (in IIS Manager- File Security - Anonymous Access - Account used for anonymous Access), but for some reason this caused the ASPX'ed to no longer recognize postbacks. There are many possible explanations for this, but considering the extra deployment effort in adding stuff to the IIS metabase we wanted another solution.
The trick is to set special impersonation for the pages that need extra authorization. In the web.config file that applies for the WebForms we added the following lines in the <configuration> element:
<location path="ASPNETVDir/SubDir/Popup/WebFormThatNeedsToAccessAD.aspx">
<system.web>
<identity impersonate="true" userName="SPSADUser" password="pwd" />
</system.web>
</location>
This ensures that the page will run with the correct user to have authorization to use DirectoryServices. Another thing to remember is that this user also needs permission to use and run the appropriate files of your web application, so make sure of that aswell.