none
Change password of user who has already expired password by using C# programming? RRS feed

  • Question

  • Hi everyone

    Actually this scenario look like changing expired password for user on OWA ; however , keep in mind that this way for my case  is intended to apply through only expired password scenario.

    The following describe user steps.

    • User enter username and password on web page and then click OK button
    • System check whether or not the password is expired.
    • If the password was expired then system will redirect to change password pages.
    • User enter current password again along with new password twice and click Submit button.
    •      Password is changed.

    -    

    As far as I researched, I found only the most likely ways is Change password method as sample below.

    In this case,I try coding as the link below

    1.  https://social.msdn.microsoft.com/Forums/en-US/68b76165-a4d6-4f22-82d2-ccca60da6d26/active-directory-changepassword-com-exception-error?forum=netfxnetcom  
    2. http://www.codeguru.com/csharp/.net/net_general/netframeworkclasses/article.php/c11413/Accessing-Directory-Services-in-NET-Framework-20.htm

     I try the code below but error

     private static bool ChangePassword()
            {
    
                // The user has been set as "User must change password at next log on"
                // It is the same as pwdLastSet=Never
                string strUserName = "joseph";
                string strOldPassword="P@ssw0rd";
                string strNewPassword="asdf+1234";
    
                const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
                const long ADS_OPTION_PASSWORD_METHOD = 7;
                const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
                const int ADS_PASSWORD_ENCODE_CLEAR = 1;
                string strPort = "389";
                int intPort;
                intPort = Int32.Parse(strPort);
    
                try
                {
    
                    string strUserString = "dev" + @"\" + strUserName.Trim();
    
                    // Use the user account you're changing the password on
                    // to validate the user really exists. Specifies the
                    // authentication type as secure
                 //   DirectoryEntry entry = new DirectoryEntry("LDAP://dev.net", strUserString, strOldPassword, AuthenticationTypes.Secure | AuthenticationTypes.Sealing | AuthenticationTypes.ServerBind);
    
                    //Instead of Administrator Account
                    DirectoryEntry entry = new DirectoryEntry("LDAP://dev.net", "dev\\administrator", "P@ssw0rd", AuthenticationTypes.Secure | AuthenticationTypes.Sealing | AuthenticationTypes.ServerBind);
    
                    DirectorySearcher search = new DirectorySearcher(entry);
                    string strFilter = "(SAMAccountName=" + strUserName + ")";
                    search.Filter = strFilter;
                    SearchResult result = search.FindOne();
                    DirectoryEntry user = result.GetDirectoryEntry();
                 
    
                    user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
                    user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
                    user.Invoke("ChangePassword", new object[] { strOldPassword, strNewPassword });
                    user.CommitChanges();
                }
                catch (Exception exception)
                {
        
                   Console.WriteLine("Change password failed for" + strUserName + "/nUser:" + exception.Message);
                    return false;
                }
                return true;
            }

    The first one, I use username and password as joseph (sample data)

    {System.Runtime.InteropServices.COMException(0x8007052E): Logon failure: unknown user name or bad password.”

    After that I try to use administrator account (domain admin) to open AD

    Having changed user/password administrator , the error is below.

    “A constraint violation occurred. (Exception from HRESULT: 0x8007202F)”

    Please advise me to deal with this issue.

    Pongthorn 


    Thursday, November 3, 2016 2:57 PM

Answers

  • Does this work?

    public void ChangeMyPassword(string domainName, string userName, string currentPassword, string newPassword)
    {
        try
        {
            string ldapPath = "LDAP://192.168.1.xx";
            DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
            if (directionEntry != null)
    
            {
                DirectorySearcher search = new DirectorySearcher(directionEntry);
                search.Filter = "(SAMAccountName=" + userName + ")";
                SearchResult result = search.FindOne();
                if (result != null)
                {
                    DirectoryEntry userEntry = result.GetDirectoryEntry();
                    if (userEntry != null)
                    {
                        userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
                        userEntry.CommitChanges();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    I referred from Here
    How to programmatically change Active Directory password

    Friday, November 18, 2016 6:17 AM

All replies

  • Hi Pongthorn,

    >>“A constraint violation occurred. (Exception from HRESULT: 0x8007202F)”

    For this error, please make sure that have enough right to change his password.

    In addition, I would suggest you using the admin ldap user to change user's password, and use setpassword instead of changepassword. Please try again.     

    Here I also find a MSDN sample code. http://code.msdn.microsoft.com/Reset-AD-User-Password-28d99a32.

    If you have any updates, please let me know.

    Best regards,

    Kristin        


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    • Edited by Kristin Xie Friday, November 4, 2016 7:29 AM
    Friday, November 4, 2016 7:28 AM
  • Hi Kristin

    Thank you for your suggestion , However It seem that SetPassword Method  isn't corresponding to my requirement.  

    As far as I am concerned , the SetPassword Method  is identical with ReSetPassword menu on AD Management UI for administrator; conversely, my issue as above mentioned topic is similar to changing password on OWA  by User (Not Admin) ,therefore  it is always required current password as figure shown in below.That's why I prefer change password method.

    I looked for a correct way for Change Password  Method  from plenty of of articles/forum on google.com  but It isn't obvious to actual solution.

    In fact  I am not sure whether Change Password method remain valid to real world implementation or not.

    I try testing as http://dunnry.com/blog/2005/03/17/NetUserChangePasswordImplementationInC.aspx

    but error as well.

    Do you have any recommendation?

    Thank you very much

    Pongthorn.

     


    Friday, November 4, 2016 8:14 AM
  • Hi Pongthorn.

    I find the detailed description about the API you called.
    https://msdn.microsoft.com/en-us/library/aa746341(v=vs.85).aspx

    Please make sure all the requirements are met and check “Remarks” section to see if you were missing something.
    Besides, based on the error code you provided, it means “Supplied credential is not valid”
    https://msdn.microsoft.com/en-us/library/aa746528(v=vs.85).aspx

    Please double confirm you provided the correct userName and password and the new password is also valid.

    Best regards,

    Kristin


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 7, 2016 2:48 PM
  • Hi Pongthorn.,

    What's the problem now? Do you have any updates now?

    Best regards,

    Kristin


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 10, 2016 9:14 AM
  • Hello Kritin,

    As far as I understand , I don't sure whether the earlier mentioned link  has been only applied to changed password on local computer  rather than active directory server or not. I try to run code but arise error as below

    Sub ChangePassword()
            Dim usr As IADsUser
            Dim szOldPass As String = "P@ssw0rd"
            Dim szNewPass As String = "P@ssw0rd1234"
    
            On Error GoTo Cleanup
    
            usr = GetObject("WinNT://dev/antony,user")
      
            Dim des As String = usr.Department
    
            usr.ChangePassword(szOldPass, szNewPass)
    
    Cleanup:
            If (Err.Number <> 0) Then
                MsgBox("An error has occurred. " & Err.Number)
            End If
            usr = Nothing
    
     End Sub


     

    Nevertheless , I try to the other  as below but It still occur error despite the face that this code is able to update use info successfully.

    Most likely ,the below change password method is the same as change password in System.DirectoryServices or even System.DirectoryServices.AccountManagement

     Sub ChangeADInfo()
            Dim usr As IADsUser
            Dim szOldPass As String = "P@ssw0rd"
            Dim szNewPass As String = "P@ssw0rd1234"
    
            ' Bind to a user object.
            usr = GetObject("LDAP://CN=antony,cn=users,DC=dev,DC=net")
    
    
            Dim name As String = usr.Name
            'usr.FullName = "Antony Blance"
            'usr.Description = "David for dev.net"
    
            'usr.SetInfo() ' Commit the changes to the directory
            usr.ChangePassword(szOldPass, szNewPass)
    
    
    
        End Sub

    apart from that , the following link https://msdn.microsoft.com/en-us/library/aa746528(v=vs.85).aspx
    This error is  "0x8007202fL LDAP_CONSTRAINT_VIOLATION There was a constrain violation."

    "


    Do you know how to deal with this problem? 

    No matter which way to change password programmatically , I cannot complete this task so far. 





    Friday, November 11, 2016 8:33 AM
  • Here is a support KB, please check if it is helpful or not

    https://support.microsoft.com/en-us/kb/947729

    Monday, November 14, 2016 6:38 AM
  • It is not related to my error.

    My error was given as below.

    Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied. (Exception from HRESULT: 0x80070547)

    I am suspicious whether the sample code of correct answer  as link below need to set additional constant configuration value or not.


    https://social.msdn.microsoft.com/Forums/en-US/68b76165-a4d6-4f22-82d2-ccca60da6d26/active-directory-changepassword-com-exception-error?forum=netfxnetcom

    const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
                const long ADS_OPTION_PASSWORD_METHOD = 7;
                const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
                const int ADS_PASSWORD_ENCODE_CLEAR = 1;



    Monday, November 14, 2016 8:09 AM
  • Does this work?

    public void ChangeMyPassword(string domainName, string userName, string currentPassword, string newPassword)
    {
        try
        {
            string ldapPath = "LDAP://192.168.1.xx";
            DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
            if (directionEntry != null)
    
            {
                DirectorySearcher search = new DirectorySearcher(directionEntry);
                search.Filter = "(SAMAccountName=" + userName + ")";
                SearchResult result = search.FindOne();
                if (result != null)
                {
                    DirectoryEntry userEntry = result.GetDirectoryEntry();
                    if (userEntry != null)
                    {
                        userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
                        userEntry.CommitChanges();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    I referred from Here
    How to programmatically change Active Directory password

    Friday, November 18, 2016 6:17 AM