Monday, July 14, 2008

Change AD Account Password via Coding

Found a few great articles on creating a custom page to allow user to change their AD login password through coding (cause I need to do one quickly here).

The new .NET Framework 3.5 provides new method from the System.DirectoryEntry.AccountManagement namespace to change password easily. Background information at here.

Steve Mushkat has a blog entry with code example on how this is done at http://glorix.blogspot.com/2007/10/ad-change-password-webpart.html. His example is base on SharePoint, but can be easily adapted for other flavours.

Update: I've tried the code on my SharePoint implementation. It worked fine on a single-box MOSS environment, but it didn't work on a small farm setup. Not sure why, but I'm suspecting the environment that didn't work did not have kerberos configured properly. I've modified the code slightly to make it workable:

string strADDomain = ConfigurationSettings.AppSettings["ChangePassword_Domain"]; string strADUser = ConfigurationSettings.AppSettings["ChangePassword_User"]; string strADPassword = ConfigurationSettings.AppSettings["ChangePassword_Password"]; string strLoginName = string.Empty; SPWeb web = SPControl.GetContextWeb(this.Context); strLoginName = web.CurrentUser.LoginName; PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, strADDomain, strADUser, strADPassword); UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, strLoginName); try { user.ChangePassword(this.txtOldPassword.Text, this.txtNewPassword.Text); this.lblMessage.Text = "Password changed. Please close this browser window and log back on with your new password."; } catch (Exception ex) { this.lblMessage.Text = String.Format("Password couldn't be changed due to restrictions: {0}", ex.Message); } finally { user.Dispose(); domainContext.Dispose(); }

No comments: