How to Authenticate LDAP in .NET

拈花ヽ惹草 提交于 2019-11-30 05:01:38

All this can be done with System.DirectoryServices.Protocols. If you create an LdapConnection to the directory you can use the service account to bind with, and then make a subsequent bind to authenticate the credentials.

The service account is generally used to limit access to the authentication mechanism of the server. This way no random person on the street can try to auth with your LDAP server.

Also, do you expect that each user will provide their distinguished name when logging in? With Active Directory, only the sAMAccountName is required, yet other providers like eDirectory and SunONE require the distinguished name for authentication.

To perform this type of authentication, you would need to use the service account that is provided to authenticate to the server, perform a search for a user with the given username, and grab that users distinguished name. You can then authenticate using that distinguished name and the password that was provided.

This will work for all LDAP systems, with the exception of Active Directory which will be happy with just the sAMAccountName.

I'm not sure I entirely understand the question, but in some situations I've found it easy to authenticate a user by simply doing a search for their account and using their credentials as the username and password.

A successful query means everything provided was correct, not finding the account means something was wrong.

//use the users credentials for the query
DirectoryEntry root = new DirectoryEntry(
    "LDAP://dc=domain,dc=com", 
    loginUser, 
    loginPassword
    );

//query for the username provided
DirectorySearcher searcher = new DirectorySearcher(
    root, 
    "(sAMAccountName=" + loginUser + ")"
    );    

//a success means the password was right
bool success = false; 
try {
    searcher.FindOne();
    success = true;
}
catch {
    success = false;
}

Probably not "best practice", but might get around your issue you are having...

We had a website that needed to authenticate a username and password against domain credentials and used the LogonUser API function. Use it for a network logon (one of its arguments is logon type) and all it does is validate credentials, it doesn't do things like load the users profile that runas would. Only caveat is that the service account does require sufficient access to call LogonUser. I suggest you check the MSDN documentation for what that access is though because it varies by OS.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!