Active directory - exception has been thrown by the target of an invocation

Bargant picture Bargant · Oct 26, 2011 · Viewed 10.3k times · Source

I have a web application in a separate server than Active Directory and I want to change a user password. The code is the next:

string newPassword = Membership.GeneratePassword(int.Parse(WebConfigurationManager.AppSettings["passLenght"]),
                                int.Parse(WebConfigurationManager.AppSettings["passNonAlpha"]));

DirectoryEntry de = new DirectoryEntry(WebConfigurationManager.ConnectionStrings["ADConnString"].ConnectionString,
WebConfigurationManager.AppSettings["ADAdmin"], WebConfigurationManager.AppSettings["ADAdminPass"]);

DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(objectClass=user) (userPrincipalName=" + name + "))";

SearchResultCollection results = deSearch.FindAll();

if (results.Count == 1)
{
   foreach (SearchResult OneSearchResult in results)
   {
      DirectoryEntry AlterUser = OneSearchResult.GetDirectoryEntry();
      AlterUser.AuthenticationType = AuthenticationTypes.Secure;
      AlterUser.Invoke("SetPassword", newPassword);
      AlterUser.CommitChanges();
      AlterUser.Close();
   }
}

When I run this in my development environment (where Active Directory and the web application are on the same server) it is working. But when I try to run it in the production environment I am having the next error:

Exception has been thrown by the target of an invocation

What am I missing?

Thanks.

EDIT:

I could go deep in the exception error and I get this:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Answer

Duncan Smart picture Duncan Smart · Oct 31, 2011

Permissions are the issue. The account under which your ASP.NET code is running doesn't have the permission to set the account password.

Either:

  • Run the AppPool under a user that has the required permissions, or
  • Use impersonation to elevate the permissions for the SetPassword call

The reason it is working in your dev environment/failing in production is likely due to a combination of:

  • You are running the app under the Visual Studio development web server that runs under your user account, which has the necessary permissions. Running it under "real" IIS will run it under a less privileged account.
  • In the live environment there's another machine hop from the web server to the AD server, and the credentials don't get passed along. The web server needs to have network credentials (either as part of the AppPool identity, or a call to LogonUser) in order to authenticate to AD.