简体   繁体   中英

Using C# to authenticate user against LDAP

I'm using DirectorySearcher to search for a user entry in LDAP server.

DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://myserver/OU=People,O=mycompany";
de.AuthenticationType = AuthenticationTypes.None;

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = de;
deSearch.Filter = "(uid=" + model.UserName + ")";

SearchResult result = deSearch.FindOne();

I'm able to get th intended output in result variable.
However If I try to authenticate the same user by providing password in directory entry, I always get following error.

"The user name or password is incorrect."

DirectoryEntry entry = new DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
DirectorySearcher search = new DirectorySearcher(
    entry,
    "(uid=" + username + ")",
    new string[] { "uid" }
);

search.SearchScope = System.DirectoryServices.SearchScope.Subtree;
SearchResult found = search.FindOne();   ->>>>>this is where I get wrong credential error.

The username and password are for the user I want to authenticate.

Can anyone tell me what I'm doing wrong here or how to debug this.

This username, password within this line:

DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);

should be for an account that has permission for directory lookup. It could be a service account or testing purpose try with your own. This shouldn't be the user/pass of someone who you are trying to authenticate.

If you want to authenticate, you can use following steps using PrincipalContext:

using(var context = new PrincipalContext(ContextType.Domain, "mydomain", "mydomain\serviceAcct", "serviceAcctPass")) {
 //Username and password for authentication.
 return context.ValidateCredentials(username, password); 
}

"serviceAcct" = an account within domain users that has permission for directory lookup. "serviceAcctPass" = password for that service account. As I said, for testing you can try with your own user/pass context.

Also, make sure supplied username has either "domain\\username" or "username@domain" formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM