首页 > 解决方案 > 如何在 C# 中的 LDAP 中进行身份验证?

问题描述

我是 LDAP 相关编码的新手,今天我被要求开发一个代码来检查用户对 LDAP 的身份验证。

我在网上找到的教程很简单,但是我们公司的目录很复杂,我不知道如何编写代码。这是 LDAP 的信息。我已更改公司名称以隐藏名称。

string domain = "ou=People,dc=my,dc=com";
string LDAP_Path= "dc01.my.com;
string LDAPconnect= "LDAP://dc01.my.com/";

这是我开发的代码,但运行“LdapResult = LdapSearcher.FindOne();”时出现错误:

    string domain = "ou=People,dc=my,dc=com";
    string password = "";
    string userName = "";

    // define your connection
    LdapConnection ldapConnection = new LdapConnection(LDAP_Path);

    try
    {
        // authenticate the username and password
        using (ldapConnection)
        {
            // pass in the network creds, and the domain.
            var networkCredential = new NetworkCredential(userName, password, domain);

            // if we're using unsecured port 389, set to false. If using port 636, set this to true.
            ldapConnection.SessionOptions.SecureSocketLayer = false;

            // since this is an internal application, just accept the certificate either way
            ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };

            // to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
            ldapConnection.AuthType = AuthType.Basic;

            // authenticate the user
            ldapConnection.Bind(networkCredential);
            Response.Write( "connect ldap success");
        }
    }
    catch (LdapException ldapException)
    {
        Response.Write(ldapException + " <p>Ad connect failed</p>");
        //Authentication failed, exception will dictate why
    }
    string strTmp0 = LDAPconnect + domain;
    string user = "memberId";
    string pwd = "memberPwd";
    System.DirectoryServices.DirectoryEntry LdapEntry = new System.DirectoryServices.DirectoryEntry(strTmp0, "cn=" + user, pwd, AuthenticationTypes.None);
    DirectorySearcher LdapSearcher = new DirectorySearcher(LdapEntry);
    LdapSearcher.Filter = "(cn=" + user + ")";
    string value = string.Empty;
    SearchResult LdapResult=null;
    try
    {
         LdapResult = LdapSearcher.FindOne();
     
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message.ToString());
 // .............get Error msg : username an password  uncorrect

    }
    if ((LdapResult != null))
    {
        Response.Write("ldapresult not null");
    }
  

   

有人可以帮忙吗?

标签: c#asp.netldap

解决方案


在 ldap 连接设置中,OP 应该使用自己的配置。

        // Ldap connection setting. this should setup according to organization ldap configuration 
        int portnumber = 12345;
        LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier("ldap.testxxxx.com", portnumber));
        ldapConnection.AuthType = AuthType.Anonymous;
        ldapConnection.Bind();

        SearchRequest Srchrequest = null;
        SearchResponse SrchResponse = null;
        SearchResultEntryCollection SearchCollection = null;

        Hashtable UserDetails = new Hashtable();
        
        Srchrequest = new SearchRequest("distniguishged name e.g. o=testxxx.com", string.Format(CultureInfo.InvariantCulture, "preferredmail=test@testxxxx.com"), System.DirectoryServices.Protocols.SearchScope.Subtree);
        SrchResponse = (SearchResponse)ldapConnection.SendRequest(Srchrequest);
        SearchCollection = SrchResponse.Entries;

        foreach (SearchResultEntry entry in SearchCollection)
        {
            foreach (DictionaryEntry att in entry.Attributes)
            {
                if (((DirectoryAttribute)(att.Value)).Count > 0)
                {
                    UserDetails.Add(att.Key.ToString(), ((DirectoryAttribute)(att.Value))[0].ToString());
                }
                else
                {
                    UserDetails.Add(att.Key.ToString(), string.Empty);
                }
            }
        }

        if (UserDetails.Count > 1)
        {
            Console.WriteLine("User exists");
        }
        else
        {
            Console.WriteLine("User does not exist");
        }

推荐阅读