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
Try
' Find the directory entry
ad = New DirectoryServices.DirectoryEntry( _
ConfigurationSettings.AppSettings("ActiveDirectoryConn"), _
ConfigurationSettings.AppSettings("ActiveDirectoryLogon"), _
ConfigurationSettings.AppSettings("ActiveDirectoryPass"))
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)
de.CommitChanges()
Catch ex As Exception
' Report Errors
Finally
de.Dispose()
ad.Dispose()
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.
Wednesday, March 10, 2004
Changing Passwords in Active Directory
Posted by Dan Agonistes at 11:13 AM
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment