FREE hit counter and Internet traffic statistics from

Wednesday, March 10, 2004

Changing Passwords in Active Directory

At a recent consulting engagement I had to write some code in VB .NET for changing a password in Active Directory in response to a user request. After looking at a few resources I decided on using the DirectorySearcher class from the System.DirectoryServices namespace to perform an LDAP (Lightweight Directory Access Protocol) search on the entire directory based on the samaccount (the account name in AD), and bring back the single DirectoryEntry that it found. I then used the Invoke method of the DirectoryEntry to call the SetPassword method, passing in the new password and committing the changes.

The end result looked like this....

Private Sub ChangePassword(ByVal account As String, ByVal newPass As String)

Dim ad As DirectoryServices.DirectoryEntry
Dim ads As Object
Dim adr As SearchResult

' Find the directory entry
ad = New DirectoryServices.DirectoryEntry( _
ConfigurationSettings.AppSettings("ActiveDirectoryConn"), _
ConfigurationSettings.AppSettings("ActiveDirectoryLogon"), _

ads = New DirectoryServices.DirectorySearcher(ad)
ads.Filter = ("(samaccountname=" & account & ")")
adr = ads.FindOne()
Dim de As DirectoryEntry = adr.GetDirectoryEntry

' Change the password
de.Invoke("SetPassword", newPass)
Catch ex As Exception
' Report Errors
End Try

End Sub

Of course, the credentials being stored unencrypted in web.config which should be addressed using the DPAPI and a custom configuration section handler using the IConfigurationSectionHandler interface.

No comments: