aashishmukherjee_ Ответов: 0

Directoryentry выдает com-исключение при попытке подключения ldap-сервера с помощью защищенного порта Подробнее см. error_secure_port_directoryentry_schema.png


Details are mentioned below
Exception snapshot
[enter image description here][1]
**STEP A**=>**Validating the proper certificate configuration**

I have a window service via which i am trying to connect the LDAP server from secure port 636 (SSL), all the certificate are properly 
configured and i have verified this using the tool ldap.exe and also check the portqry tool to check if the port 636 is listening or not
and **was successful in doing that**.


**STEP B=>Code Snippet Which is not working for secure port 636(For SSL) but working correctly with non secure port (389)
A strange observation the Below  mention code works well when i run it as console based application even with port 636 but fails when run as window service.**

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace SampleLDAPWindowsService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
           
            TestDirectoryEntryWay();
            
        }

        protected override void OnStop()
        {
            

        }
           
        }
        public DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings  
            DirectoryEntry ldapConnection = null;
            ldapConnection = new DirectoryEntry("LDAP://abc.domain.com:636", "DomainAdmin", "DomainAdmin123", AuthenticationTypes.SecureSocketsLayer);
            return ldapConnection;
        }

        public void TestDirectoryEntryWay()
        {
            DirectorySearcher _searcher = null;
            SearchResult result_user = null;
            DirectoryEntry de = createDirectoryEntry();
            try
            {
                object o = de.SchemaEntry;//Getting a com exception  as the SchemaEntry is null not sure why as the same is working properly in port 389 
                _searcher = new DirectorySearcher(de, "(&(objectClass=user)(SAMAccountName=" + "demouser1" + "))");
                if (_searcher != null)
                {
                    result_user = _searcher.FindOne();
                   
                }
            }
            catch (Exception ex)
            {
				//Getting a com exception 
         
            }
            
        }
    }
}

**STEP C=>Code which is working in both port 636 and port 389 in window service**
<pre lang="c#">using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    using System.DirectoryServices.Protocols;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace SampleLDAPWindowsService
    {
        public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {
                System.Diagnostics.Debugger.Launch();
                // TestDirectoryEntryWay();
                var isLogged2 = SignInLDAP2("DomainAdmin", "DomainAdmin123", ""LDAP://abc.domain.com:636"", "abc.domain.com", true);
            }
    
            protected override void OnStop()
            {
                
    
            }
    
            public  bool SignInLDAP2(string user, string psw, string ldapPath, string domain = null, bool useSSL = false)
            {
                // LdapConnection ldapConnection = new LdapConnection(ldapPath);
    
                var ldapDirectoryIdentifier = new LdapDirectoryIdentifier("abc.domain.com", 636, true, false);
                LdapConnection ldapConnection = new LdapConnection(ldapDirectoryIdentifier);
    
                if (useSSL)
                {
                    ldapConnection.SessionOptions.SecureSocketLayer = true;
    
                    ldapConnection.AuthType = AuthType.Negotiate;
                    
                    ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
                }
    
                //var networkCredential = new NetworkCredential("Hey", "There", "Guy");
                var networkCredential = new NetworkCredential(user, psw, domain);
                try
                {
                    ldapConnection.Bind(networkCredential);
    
                    bool exists = UserExists("demouser1");
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            public bool UserExists(string username)
            {
                // create your domain context
                using (PrincipalContext domain = new PrincipalContext(ContextType.Domain, "abc.domain.com", "DomainAdmin", "DomainAdmin123"))
                {
                    // find the user
                    UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
    
                    return foundUser != null;
                }
            }
           
         
                
            }
        }
    }


**Вопрос вот в чем**

Есть ли проблема при работе с защищенным портом с DirectoryEntry, так как LdapConnection & networkCredential работает плавно с обоими портами(636 &389),
у меня есть унаследованный код, который использует DirectoryEntry, и я хочу, чтобы он работал и для безопасного порта, может ли кто-нибудь помочь мне, как сделать шаг B работающим для безопасного порта
тоже.

Заранее спасибо за всю ту поддержку, &ампер; руководство.


Что я уже пробовал:

Уже обеспечено, что служба окон используется в локальной системе, проверена правильная установка сертификата путем подключения инструмента, такого как ldapadmin и ldap.exe для порта 636 с проверкой ssl.

0 Ответов