簡體   English   中英

如何在 C# 中的 LDAP 中進行身份驗證?

[英]How to authenticate in LDAP in C#?

我是 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");
    }
  

   

有人可以幫忙嗎?

在 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");
        }

您可以使用具有用戶名和密碼 arguments 的 DirectoryInfo 構造函數 這樣,您無需查詢 LDAP,即可簡化代碼。

string username = "frederic";
string password = "myFanciPassword99";

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

string connectionString = LDAPconnect + domain;

bool userValid = false;

// Note: DirectoryEntry(domain, username, password) would also work
DirectoryEntry entry = new DirectoryEntry(connectionString, username, password);
try
{
    // Bind to the native AdsObject to force authentication.
    Object obj = entry.NativeObject;
    userValid = true;
}
catch (Exception ex)
{
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM