Reputation: 103
I'm hoping someone can explain this to me because I am at my wits end trying to resolve an issue I am having.
The error I am receiving is, "The object already exists." whenever I am trying to run our ResetPassword function. The weird thing is I ONLY receive this error if the user account has had their password reset before. If I either create a new account with a new password, or search for a user in the database that has not had the ResetPassword function called on their account, then it will let me call this function once. Note: On this one time it lets me run the function the password does get reset. Any account that has already run ResetPassword will prompt the object already exists error.
public static void ResetPassword(DirectoryEntry User, string password)
{
User.Invoke("SetPassword", new object[] { password });
User.Properties["LockOutTime"].Value = 0x0000; //unlock account
int val = (int)User.Properties["userAccountControl"].Value;
User.Properties["userAccountControl"].Value = val & ~0x2; //Enable account
User.CommitChanges();
Logs.CreateLogEntry("Reset password", User);
User.Close();
}
As you can see, we are passing in a DirectoryEntry user, along with a generated new password. We are using an anonymous login on the backend of our IIS website to have admin credentials high enough to use SetPassword.
Upvotes: 0
Views: 522
Reputation: 126
You need to provide credentials of a user in AD that has admin privileges to reset passwords.
public static void ResetPassword(string username, string password)
{
string adminUser = "YourAdminUserIdInAD";
string adminPass = "YourAdminUserPasswordInAD";
string ldapString = "LDAP://YourLDAPString";
DirectoryEntry dEntry = new DirectoryEntry(ldapString , adminUser, adminPass, AuthenticationTypes.Secure);
DirectorySearcher deSearch = new DirectorySearcher(dEntry) {
SearchRoot = dEntry,
Filter = "(&(objectCategory=user)(cn=" + username + "))"
};
var directoryEntry = deSearch.FindOne();
directoryEntry.Invoke("SetPassword", new object[] { password });
directoryEntry.Properties["LockOutTime"].Value = 0x0000; //unlock account
int val = (int)directoryEntry.Properties["userAccountControl"].Value;
directoryEntry.Properties["userAccountControl"].Value = val & ~0x2;
directoryEntry.CommitChanges();
Logs.CreateLogEntry("Reset password", User);
directoryEntry.Close();
}
Upvotes: 0