管理员无法使用 C# .NET Core 6 重置活动目录用户密码



我试图通过.NET核心web API重置active directory用户密码,但总是返回异常以下,即使我放入非常复杂的密码

System.DirectoryServices.AccountManagement.PasswordException:'密码不符合密码策略要求。检查最小密码长度、密码复杂性以及密码历史记录要求。(0x800708C5('

我尝试了两种方法(DirectoryEntry和新方法(,但得到了相同的异常。

这是我的代码,但我认为

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;
}
}

以下代码运行良好,重置密码时不需要旧密码,需要帐户所有者用户名:

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;
}
}

最新更新