Reset AD User Password with C# and ASP.NET

A sample project to show how to search for a user in Active Directory and reset that users password to the string password.The sample will build out of the box. To make it work you will need the following information in the web.config adAdminUser - Username that has permission t

C# (6.3 MB)
 
 
 
 
 
(1)
8,119 times
Add to favorites
9/15/2011
E-mail Twitter del.icio.us Digg Facebook
Sign in to ask a question


  • error
    3 Posts | Last post June 20, 2014
    • when i click the "reset password",i get the errors look like this :
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
      
      Exception Details: System.DirectoryServices.DirectoryServicesCOMException: the server does not want to handle the request.。 (Exception from HRESULT: 0x80072035)
      
      Source Error:
      
      An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
      
      Stack Trace:
      
      
      [DirectoryServicesCOMException (0x80072035): the server does not want to handle the request. (Exception from HRESULT: 0x80072035)]
      
      [TargetInvocationException: Exception has been thrown by the target of an invocation.]
         System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) +636829
         Sample.ResetADPassword.Web.ResetPassword.ResetUserPassword(Object sender, EventArgs e) in C:\Users\Niall\Desktop\Sample\Sample.ResetADPassword\Sample.ResetADPassword.Web\ResetPassword.aspx.cs:21
         System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
         System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3691
      
    • Best guess, you are setting a weak password that the domain server will not honor. check the complexity requirements and see if can set that password on the user normally
    • i set the password  like this"P@ssw0rd", and sometimes ago ,i can change the password,and also get the error, but now ,it can't change the password,and get the same error. i can not find the problem.
  • Hi sir
    2 Posts | Last post November 18, 2013
    • 1. I want to create a page to change AD passwords for all users (not reset). Could you tell me how can I config for my code running. 
      2. Do I need admin account of AD???
      3. What permission will be assigned?
      
    • THat would require a bit of work.. you would need to get a list of all users in the AD and then loop through it. 
      
      Permission wise.. Account Operator would be sufficient I think.
      
      I dont understand #3
  • Got error when searching my user with name like "administrator"
    2 Posts | Last post July 04, 2013
    • Hi Niall, 
      I m implementing user change password functionality and used ur code for testing but i got an exception when it calling getdirectoryentrybyusername function ..
      exception like "referral was returned from server ". what does it means?
    • Hi
      
      Most likely the issue is that the code that is used to build the connection string is finding the incorrect server. 
      
      You can modify the code to allow referrals by changing the function
      
        public static DirectoryEntry GetDirectoryEntryByUserName(string userName) 
              { 
                  var de = GetDirectoryObject(GetDomain()); 
                  var deSearch = new DirectorySearcher(de) 
                                                   {SearchRoot = de, Filter = "(&(objectCategory=user)(cn=" + userName + "))"}; 
      
      /*
      New addition
      */            
      
      deSearch.ReferralChasing = ReferralChasingOption.All;
                  var results = deSearch.FindOne(); 
                  return results != null ? results.GetDirectoryEntry() : null; 
              } 
  • Help me to fix this problem, When I used your code with little modification for reset password?
    8 Posts | Last post December 10, 2012
    • Here is the error
      
      Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) 
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
      
      Exception Details: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) 
      
      ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user. 
      
      To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
      
      
      An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  
      
      Stack Trace: 
      
      
      [UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))]
      
      [TargetInvocationException: Exception has been thrown by the target of an invocation.]
         System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) +632905
         ResetADPassword.ResetUserPassword(Object sender, EventArgs e) +136
         
    • It looks like you took out the code that supplies the credentials or you dont have the correct permissions in the first place... What change did you make?
    • I am Modify only GetDirectoryEntryByUserName(string userName)
      I have to modify anthing in IIS server..
      Thanks For all your help in advance..
      
      Here is the code
      public static DirectoryEntry GetDirectoryEntryByUserName(string userName)
          {
      
      
              DirectoryEntry ldapConnection = new DirectoryEntry();
              ldapConnection.Path = "LDAP://xxx.xxx.xxx/OU=xxx,DC=xxx,DC=xxx";
              ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
              DirectorySearcher search = new DirectorySearcher(ldapConnection);
              search.Filter = "(&(objectClass=user)(SamAccountName=" + userName + "))";    //this way cannot get mail property
              // search.Filter = "(&(objectClass=user)(cn=smith john)(c=UK))";		   //this works fine
              SearchResult result = search.FindOne();
      
              if (result != null)
              {
                  return result.GetDirectoryEntry();
      
              }
              else
              {
                  return null;
      
      
              }
      
          }
    • Ok I see the issue. You removed the authenticated directory entry that I used.
      
      I used var de = GetDirectoryObject(GetDomain()); which returned back a directory entry using a specific account that has account operator privileges or higher. This means that when I accessed properties in the directory I was doing so under the other account rather than the IIS process account.
      
      To make this work you can do a couple of things. 
      
      1. Use impersonation - The application acts as if its the user. You can set this in the web.config by using Windows authentication and <identity impersonate="true"/> 
      
      The user will need to have the appropriate permissions to change users passwords in the domain.
      
      2. Run the application as a highly privelaged account (NOT ADVISED!!! I am only adding this for the sake of completeness!) Do not use this method please!
      
      
      
      
    • When I use code exactly what you gave..
      I am getting this error
      Unknown error (0x80005000) 
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
      
      Exception Details: System.Runtime.InteropServices.COMException: Unknown error (0x80005000)
      
      Source Error: 
      
      
      Line 32:                                              {SearchRoot = de, Filter = "(&(objectCategory=user)(cn=" + userName + "))"}; 
      Line 33:              
      Line 34:             var results = deSearch.FindOne(); 
      Line 35:             return results != null ? results.GetDirectoryEntry() : null; 
      Line 36:         } 
       
      
      Source File: t:\dev.avila.edu\VS2010\LDAP\Default.aspx.cs    Line: 34 
      
      Stack Trace: 
      
      
      [COMException (0x80005000): Unknown error (0x80005000)]
         System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +378094
         System.DirectoryServices.DirectoryEntry.Bind() +36
         System.DirectoryServices.DirectoryEntry.get_AdsObject() +31
         System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) +78
         System.DirectoryServices.DirectorySearcher.FindOne() +47
         _Default.GetDirectoryEntryByUserName(String userName) in t:\dev.avila.edu\VS2010\LDAP\Default.aspx.cs:34
         _Default.ResetUserPassword(Object sender, EventArgs e) in t:\dev.avila.edu\VS2010\LDAP\Default.aspx.cs:21
      
       
      Why I am getting this error That is why I change like above
    • Hi
      
      Sorry for the delay...
      
      In the web.config are you using an admin username and password .. the admin username should be in the form domain\username
      
      
    • Niall,
      
      is this code applicable to reset the users password outside the domain ?
      I have a requirement that i need to create a web form to reset the password for our employee outside the domain. I have given a username and password from the AD which has Administrative acess. Can you guide me what would be the best approach for me.
      Thank you !
      -Kevin
    • If there is a trust between the domains, it could be used. To be honest, I havent tested it on multiple domains.
      
      The account that runs the updates needs account operator permissions on the domain that it will be changing the password on. 
      
      To make this work from one domain to another, the application server would need to be trusted in both domains (or there should be a trust between the servers domain and the external domain)