- I found many articles on web explaining how to authenticate users using ContextType.Domain with PrincipalContext, very few explaining how to authenticate ContextType.ApplicationDirectory with PrincipalContext object but none explaining how do you authenticate individual users in LDAP when you actually connect to a root(or service account).
- Create a PrincipalContext first using the correct parameters: ContextType.ApplicationDirectory, [SERVERNAME:PORT], [Container – Distinguised name of top level root],[USERNAME],[PASSWORD]. Use the root username and password here
- After making sure that the PrincipalContext is created properly(ConnectedServer property of PrincipalContext should be set properly), get a UserPrincipal object by calling the static FindByIdentity() method on UserPrincipal class and pass in the PrincipalContext just created and the [username] as the second parameter.
- Create a DirectoryEntry object by calling GetUnderlyingObject() method on the UserPrincipal object created in step 2.
- Set a password for this DirectoryEntry object created in step 3.
- Create a temp variable of type object by calling NativeObject property of DirectoryEntry object created in step 4. At this stage, it should fail if the password is invalid. If password is valid, i will simply move on.
So if you get a PrincipalContext using a service account then you can only ValidateCreditials for that service account. But if you create more users in that DirectoryStore as new “user objects”, then you can’t authenticate them using PrincipalContext object. You can get a UserPrincipal object by using FindByIdentity() method and passing the PrincipalContext, however UserPrincipal doesn’t have ValidateCredential method. It will return you that child user object from the tree but you can check directly if a supplied password matches with the one stored in AD. You can’t even check it manually because Password property is not exposed. So how to do that? Here is what you need to do:
These steps are important to do authentication of individual users. With ContextType.ApplicationDirectory, we have to followed this convoluted path to authenticate users.
For ContextType.Domain, its fairly simple. You can just get a PrincipalContext object by just passing the ContextType.Domain and Domain name as the two parameters to constructor and just call ValidateCredentials and pass different username/password combinations.
Have a good day!