
If you need a solution that allows users to quickly change their NT account passwords on a web server that resides outside of their domain, you can use the
DirectoryServices namespace. One example of when this might be necessary is in the case of a Windows SharePoint Service site that is exposed to an external set of users. The code below and attached solution shows how to do this.
You begin by adding a reference to the System.DirectoryServices.dll assembly. Next, create a web form with 2 Labels, 2 Textboxes and a Button control, like the one shown below:
In the code behind, add the following:
string userName = string.Empty;
protectedvoid Page_Load(object sender, EventArgs e)
{
userName = HttpContext.Current.User.Identity.Name.ToString();
lblLoggedInUser.Text = userName.Split('\\')[1];
lblMessage.Text = string.Empty;
lblMessage.ForeColor = System.Drawing.Color.Red;
}The first 2 lines of code in the Page_Load event get the current user’s domain and user name and writes the user name portion to the label control. Putting the user name in a label control versus a text box prevents users from changing the passwords of users. Next, add the following code and wire this event to the Button’s Click event:
protected void btnResetPassword_Click(object sender, EventArgs e)
{
try
{
string user = userName.Split('\\')[1];
DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
DirectoryEntry NewUser = AD.Children.Find(user);
NewUser.Invoke("SetPassword", newobject[] {txtConfirmPassword.Text});
NewUser.CommitChanges();
lblMessage.Text = "Password change successful.";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
catch (Exception err)
{
// set the error message
Response.Write(err.Message);
}
}
}The first three lines in the code above create an instance of the DirectoryEntry class based on the name of the computer and then query that computer for the specific user. Once the directory entry for that user is located, the Invoke method is called on the directory entry, passing in the command argument for setting the new password. This is followed by a call to the CommitChanges method. Lastly, in order to run this code on the web server, the web.config file needs to be modified so that the solution impersonates a user with privileges to update security settings:
<identity impersonate="true" userName="user" password="pwd"/>
Once the page is made available on the server, you can integrate it with SharePoint by adding a link to the SharePoint site, or by linking to it through a Page Viewer web part.
Comments
Leave a Comment