In order to execute code that needs specific permissions to your Active Directory, follow these steps:
- Require the user to log into the ASP.NET application.
- Have your code impersonate the currently-logged in user when executing the the Active Directory portion that needs that access.
There may be slight variations depending on the version of ASP.NET you are using, but basically...
Step 1
For the user login, just use the standard ASP.NET authentication configuration. Because it's the easiest to configure (and just works with AD) I'll document Windows Authentication here. This will prompt the user with a standard Windows login dialog box - where they will need to enter their domain credentials. To configure the application, make the following changes to the Web.config
<configuration>
...
<system.web>
...
<authentication mode="Windows" />
...
</system.web>
...
</configuration>
By default, ASP.NET should already know how to talk to the Active Directory when configured for Windows Authentication, so nothing else should be required, but if you find you need a separate Role Provider, feel free to take the one we use. (We also have instructions.) But again, you shouldn't need it.
Edit: You also need to make sure IIS is configured - using inetmgr.exe
- to not allow anonymous access for the application. Otherwise, it will never prompt the user to log in. We typically disable Anonymous access and enable Windows and Basic authentication - because we need to support browsers that don't support NTLM.
Step 2
Now that you have an authenticated user, you can programmatically impersonate them. The following is adapted from Impersonating the authenticating user in code:
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
try
{
// Do your writing to the AD here
}
finally
{
impersonationContext.Undo();
}
I also just discovered (while searching for reference links for this answer) that this is all pretty well documented in the MSDN article How To: Use Windows Authentication in ASP.NET 2.0
Let us know how it goes :-)