I'm using System.DirectoryServices
to query active directory to authenticate/fetch users' info in a winforms appliation. Something like below:
var path = "LDAP://" + domain;
var entry = new DirectoryEntry(path);
DirectorySearcher myDirectorySearcher = new DirectorySearcher(entry);
var filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);
myDirectorySearcher.Filter = filter;
I can only test this code on company's Active Directory. Is this going to work on any technology that supports LDAP
?
The System.DirectoryServices
namespace is optimized for Active Directory. It will work against other LDAP servers - with certain limitations.
There's also the System.DirectoryServices.Protocols
(see MSDN documentation and intro MSDN article) namespace (new in .NET 2.0) which is more of a low-level LDAP implementation - you need to do more work and write more code, but it's more portable and more likely to work with other LDAP stores.
There's also the System.DirectoryServices.AccountManagement
(see MSDN documentation) namespace (new in .NET 3.5) which is a much nicer and simpler approach to using Active Directory from .NET - much improved over the S.DS stuff! But this is Active Directory only as far as I can tell.
You should change the filter to look like this:
var filter = string.Format("(&(objectCategory={0})(objectClass={1})(sAMAccountName={2}))", "person", "user", username);
This isn't going to generically work with any LDAP directory, though. sAMAccountName
, for example, is an AD specific attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With