I'm Trying to reset active directory user password by .NET core web API but always return below exception, even if I put very complex password
System.DirectoryServices.AccountManagement.PasswordException: 'The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. (0x800708C5)'
I tried both ways (DirectoryEntry
and the new one) but I get the same exception.
Here is my code, but I think
public bool ResetPassword(string oldPassword, string newPassword, string userNameI)
{
/* // set up domain context
PrincipalContext context = new PrincipalContext(ContextType.Domain, LDAP_PATH, userName, password);
if (context != null)
{
// find the user you want to delete
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userNameI);
if (user != null)
{
user.Enabled = true;
user.ChangePassword(oldPassword,newPassword);
user.ExpirePasswordNow();
user.Save();
return true;
}
}*/
/*
var entry = new DirectoryEntry
{
Path = "LDAP://MyIP",
Username = userName,
Password = password
};
using (var searcher = new DirectorySearcher(entry))
{
searcher.Filter = "(SAMAccountName=" + userNameI + ")";
var result = searcher.FindOne();
var user = result.GetDirectoryEntry();
user.Invoke("ChangePassword", new object[] { oldPassword.Trim(), newPassword.Trim() });
user.CommitChanges();
return true;
}
*/
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "LDAPIP", userName, password))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userNameI))
{
if (user != null)
{
user.ChangePassword(oldPassword, newPassword);
user.Save();
return true;
}
else
{
throw new Exception(string.Format("Username not found: {0}", userNameI));
}
}
return false;
}
}
The below code is working fine, the Old password is not needed in resetting password and account owner user name is needed :
public bool ResetPassword(string newPassword, string accountOwneruserName /*user name for the user that you want to change his password*/)
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "17x.xx.xx.x" /*Active Directory server Ip*/, adminUserName, adminPassword ))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, accountOwneruserName))
{
if (user != null)
{
user.SetPassword(newPassword.Trim());
user.Save();
return true;
}
else
{
throw new Exception(string.Format("Username not found: {0}", accountOwneruserName));
}
}
return false;
}
}