Thursday, June 12, 2008

How to change a user's password in Active Directory with Directory Services and C#

How to change a user's password in Active Directory with Directory Services and C#
How to change a user's password in Active Directory with Directory Services and C#

Below is a code snippet that I hope will be helpful. There are some obvious assumptions made - that the user has experience coding in Directory Services and C# - let me know if you would like more info.

private const string GETUSERID_QUERY = "((&(objectClass=user)(samAccountName={0}))(&(objectClass=contact)(displayName={0})))";

public bool ChangePassword(string rootDSE, string userName, string newPassword) { // Here, the rootDSE is already set, so is the user's name and their desired new password. // We'll call a sub that will resolve the user's name to their ID in AD and invoke the change password on that userID // You can do something as simple as DirectoryEntry root = new DirectoryEntry() - that'll return your root to you... // User name is the same as Context.User.Identity.Name - their loginID (please forgive any typoes - I'm not using a dev env for this)...
using(DirectoryEntry userEntry = GetUserByLoginID(root, username)) { try { userEntry.Invoke("SetPassword", new object[] { newPassword }); userEntry.Invoke("SetInfo"); // It's possible you might not even need this call...
userEntry.CommitChanges();
} catch(System.Reflection.TargetInvocationException err) { throw new PasswordPolicyException(comError.Message,comError); /// Assuming you have a method to handle this... } } }
private DirectoryEntry GetUserByLoginID(string rootDSE, string userID) { using (DirectoryEntry searchRoot = new DirectoryEntry(rootDSE)) { using (DirectorySearcher searcher = new DirectorySearcher(searchRoot, String.Format(GETUSERID_QUERY, userID))) { SearchResult searchResult = searcher.FindOne(); if (searchResult==null) return null; else return searchResult.GetDirectoryEntry(); } } }

No comments: