Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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))

like image 597
Bargant Avatar asked Dec 28 '22 12:12

Bargant


2 Answers

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.
like image 87
Duncan Smart Avatar answered Feb 25 '23 04:02

Duncan Smart


The code looks correct. This could be happening because the password your sending though Active Directory does not meet the minimum requirements. Trying using a more complex password such as "M2k3ThisWork!"

like image 34
RichD Avatar answered Feb 25 '23 04:02

RichD