I have a project, to create a web interface to let user login to and change their Active Directory(AD) password. Never been touching the AD for my life, this being the great explore for me to deal with AD object in .NET framework.
To be able to access to AD, we will need to include a reference to our project, to include a System.DirecotryServices dll into our web project. In order to use the DirectoryEntry class, an imports statement will be needed, as following,
Imports System.DirectoryServices
To keep things simple, as I promised myself before I start the project, giving a visit to MSDN, I learnt that the LDAP path to the AD is something like this: LDAP://litwareinc/CN=Users,DC=litwareinc,DC=com
, the litwareinc will be the domain name and the DC=com will the the .com thing (yes, I guess it). From the Internet, I learn a method to be call to change the password will be ChangePasswordand SetPassword. The SetPassword is the method that act as administrator, which does not need to specify a old password, so the suitable method for my case will be the ChangePassword.
First to create a DirectoryEntry object, I will need to provide the path to our AD, which is the LDAP://litwareinc/CN=Users,DC=litwareinc,DC=com
, after that we need to invoke the ChangePassword method from the DirectoryEntry object, it will looks something like this:
Dim deObj As New DirectoryEntry("LDAP://litwareinc/CN=Users, DC=litwareinc, DC=com", UserName, Password, AuthenticationTypes.Secure)
deObj.Invoke("ChangePassword", New Object(){OldPassword, NewPassword})
First run, the above codes threw me an exception Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))
. after doing some trial and error, realized that I need to specified the user’s display name at the path, e.g. I want to change the name for user Amy Alberts, which using AmyA as login name, and my AD path should be LDAP://litwareinc/CN=Amy Alberts,CN=Users,DC=litwareinc,DC=com
.
The question came, people won’t input their full name when they login, how do I retrieve the full name based on the login ID? From Object Viewer, I found something useful, DirecotrySearcher
, which allow me to set filter on the DirectoryEntry object created previously. OK, solved first problem, yet another came, what is the filter string looks like? Another wild guess (no harm from guessing), it will search by the properties, or maybe part of the key in the path. To find out list of the properties available, I will need to cycle through the DirectoryEntry’s child and print it out (day 2 of the project, which is the state I start coding, I don’t have Internet access, have to do it the hard way :S).
Read more ... →