当前位置: 首页>>代码示例>>C#>>正文


C# Protocols.LdapConnection类代码示例

本文整理汇总了C#中System.DirectoryServices.Protocols.LdapConnection的典型用法代码示例。如果您正苦于以下问题:C# LdapConnection类的具体用法?C# LdapConnection怎么用?C# LdapConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


LdapConnection类属于System.DirectoryServices.Protocols命名空间,在下文中一共展示了LdapConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: enableCompId

        /// <summary>
        /// This method is to help enable the compound identity feature on the computer account in the specific domain.
        /// </summary>
        /// <param name="domainName">The domain name of the service principal.</param>
        /// <param name="computerName">The host name of the service principal.</param>
        /// <param name="adminName">Need administrator's credential to modify active directory account.</param>
        /// <param name="adminPwd">Need administrator's credential to modify active directory account.</param>
        public void enableCompId(string domainName, string computerName, string adminName, string adminPwd)
        {
            LdapConnection connection = new LdapConnection(domainName);
            NetworkCredential cred = new NetworkCredential(adminName, adminPwd, domainName);
            connection.Credential = cred;
            string dn = PacHelper.GetDomainDnFromDomainName(domainName);
            string targetOu = "cn=Computers," + dn;
            computerName = computerName.Replace("$", "");
            string filter = "cn=" + computerName;
            string[] attributesToReturn = new string[] { "msDS-SupportedEncryptionTypes" };
            SearchRequest searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);

            SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
            SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;

            object attributeValue = null;
            attributeValue = PacHelper.getAttributeValue(attributes, "msDS-SupportedEncryptionTypes");
            uint? supportedEncTypes = (uint?)Convert.ToInt32(attributeValue);

            uint compIdFlag = 131072;
            if ((supportedEncTypes.Value & compIdFlag) != compIdFlag)
            {
                string computerDN = filter + "," + targetOu;
                supportedEncTypes = supportedEncTypes + compIdFlag;
                ModifyRequest modRequest = new ModifyRequest(computerDN, DirectoryAttributeOperation.Replace, "msDS-SupportedEncryptionTypes", supportedEncTypes.ToString());
                ModifyResponse modResponse = (ModifyResponse)connection.SendRequest(modRequest);
            }
        }
开发者ID:yazeng,项目名称:WindowsProtocolTestSuites,代码行数:35,代码来源:SutControlAdapter.cs

示例2: GetLdapConnection

        /// <summary>
        /// Static Method used to create an LDAP connection object
        /// </summary>
        /// <param name="credential">User Credential</param>
        /// <param name="ldapConfigRepository">Repository of all LDAP configuration</param>
        /// <returns></returns>
        public static LdapConnection GetLdapConnection(NetworkCredential credential,
            ILdapConfigRepository ldapConfigRepository)
        {
            var ldapConnection = new LdapConnection(ldapConfigRepository.GetServer())
            {
                AuthType = ldapConfigRepository.GetAuthType()
            };
            ldapConnection.SessionOptions.ProtocolVersion = 3;

            if (ldapConfigRepository.GetSecureSocketLayerFlag())
                ldapConnection.SessionOptions.SecureSocketLayer = true;

            if (ldapConfigRepository.GetTransportSocketLayerFlag())
                ldapConnection.SessionOptions.StartTransportLayerSecurity(null);

            if (ldapConfigRepository.GetClientCertificateFlag())
            {
                var clientCertificateFile = new X509Certificate();
                clientCertificateFile.Import(ldapConfigRepository.GetClientCertificatePath());
                ldapConnection.ClientCertificates.Add(clientCertificateFile);
                ldapConnection.SessionOptions.VerifyServerCertificate += (conn, cert) => true;
            }

            return ldapConnection;
        }
开发者ID:barrett2474,项目名称:CMS2,代码行数:31,代码来源:LdapConnectionFactory.cs

示例3: CreateLdapConnection

 public static LdapConnection CreateLdapConnection(OcesEnvironment environment)
 {
     var ldapServerName = Properties.Get("ldap.server.danid." + environment);
     var ldapConnection = new LdapConnection(ldapServerName) { AuthType = AuthType.Anonymous };
     ldapConnection.SessionOptions.ProtocolVersion = 3;
     return ldapConnection;
 }
开发者ID:hgaard,项目名称:OOAPI,代码行数:7,代码来源:LdapFactory.cs

示例4: ValidateCredentials

        public bool ValidateCredentials(ICollection<Credential> credentials, string password, out Credential matched)
        {
            var ldapCred = credentials.FirstOrDefault(c => c.Type == CredentialType_LdapUser);
            matched = ldapCred;
            if (ldapCred != null)
            {
                try
                {
                    LdapConnection connection = new LdapConnection(this.Configuration.Server);
                    connection.SessionOptions.SecureSocketLayer = true;
                    connection.SessionOptions.VerifyServerCertificate = (ldapConnection, certificate) =>
                    {
                        return true;
                    };
                    connection.AuthType = AuthType.Negotiate;

                    NetworkCredential credential = new NetworkCredential(ldapCred.Value, password);
                    connection.Credential = credential;
                    connection.Bind();

                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }

            return false;
        }
开发者ID:goitsk,项目名称:NuGetGallery,代码行数:30,代码来源:LdapService.cs

示例5: GetSearchResponse

        public static SearchResponse GetSearchResponse(string searchFilter, string searchBase, int sizeLimit = 500)
        {
            //Establishing a Connection to the LDAP Server
            //var ldapident = new LdapDirectoryIdentifier(STR_LDAPURL, STR_LDAPPort);
            var ldapident = new LdapDirectoryIdentifier(STR_LDAPOLD, STR_LDAPPort);
            //LdapConnection lc = new LdapConnection(ldapident, null, AuthType.Basic);
            using (var lc = new LdapConnection(ldapident, new NetworkCredential(LDAPUser, LDAPPassword), AuthType.Basic))
            {
                lc.SessionOptions.ProtocolVersion = 3;
                lc.SessionOptions.SecureSocketLayer = true;
                lc.SessionOptions.VerifyServerCertificate = (connection, certificate) => true;
                lc.Bind();

                //Configure the Search Request to Query the UCD OpenLDAP Server's People Search Base for a Specific User ID or Mail ID and Return the Requested Attributes
                var attributesToReturn = new string[]
                                         {
                                             STR_UID, STR_EmployeeNumber, STR_Mail, STR_Telephone, STR_DisplayName, STR_CN,
                                             STR_SN, STR_GivenName, STR_PIDM
                                         };

                var sRequest = new SearchRequest(searchBase, searchFilter, SearchScope.Subtree, attributesToReturn) { SizeLimit = sizeLimit };

                //Send the Request and Load the Response
                var sResponse = (SearchResponse)lc.SendRequest(sRequest);

                return sResponse;
            }
        }
开发者ID:ucdavis,项目名称:Purchasing,代码行数:28,代码来源:DirectorySearchService.cs

示例6: authenticateBoundary

        public User authenticateBoundary(string email, string password)
        {
            ldapId = new LdapDirectoryIdentifier(HOST, PORT);
            network = new NetworkCredential(DN.Replace("{0}", email), password);

            using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
            {
                try
                {
                    connection.SessionOptions.SecureSocketLayer = false;
                    connection.SessionOptions.ProtocolVersion = 3;
                    connection.Bind();

                    connection.Dispose();

                    return queryLdap(email);
                }
                catch (LdapException ex)
                {
                    throw new BusinessException(ex.Message);
                }
                catch (Exception e)
                {
                    throw new PlatformException(e.Message);
                }
            }
        }
开发者ID:arciniegas88,项目名称:TouresBalon-Enterprise,代码行数:27,代码来源:SecurityBoundary.cs

示例7: StringValues

        /// <summary>
        /// Typical usage:
        /// foreach (string s in RangeHelper.StringValues(conn, "cn=test", "member", 0, null, false))
        ///  ....
        /// 
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="entryDn"></param>
        /// <param name="attrName"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public static IEnumerable<string> StringValues(LdapConnection conn, string entryDn, string attrName, int start, int? end, bool extendedDns)
        {
            int requested = 0, returned = 0;
            if (end != null)
                requested = end.Value - start;

            RangeResult r = GetRangeBlock(conn, entryDn, attrName, start, end, extendedDns);
            while (r != null)
            {
                foreach (string s in r.Values)
                {
                    if (requested > 0 && ++returned >= requested)
                        yield break;

                    yield return s;
                }

                if (r.IsFinal)
                    yield break;
                else
                    r = GetRangeBlock(conn, entryDn, attrName, r.End + 1, end, extendedDns);
            }

            yield break;
        }
开发者ID:skradel,项目名称:Zetetic.Ldap,代码行数:37,代码来源:RangeHelper.cs

示例8: Connect

        public LdapState Connect(NetworkCredential credential)
        {
            try
            {
                _ldapConnection = LdapConnectionFactory.GetLdapConnection(credential, _configRepository);
                if (_adminModeChecker.IsAdminMode()) _ldapConnection.Bind(credential);
                if (_adminModeChecker.IsAnonymousMode()) _ldapConnection.Bind(credential);
            }
            catch (Exception e)
            {
                string errorConnectionMessage = String.Format("{0}\n User: {1}\n Pwd: {2}{3}{4}{5}",
                    e.Message,
                    credential.UserName,
                    credential.Password,
                    (_configRepository.GetSecureSocketLayerFlag() ? "\n With SSL " : ""),
                    (_configRepository.GetTransportSocketLayerFlag()? "\n With TLS " : ""),
                    (_configRepository.GetClientCertificateFlag() ? "\n With Client Certificate" : ""));
                _logger.Write(_logger.BuildLogMessage(errorConnectionMessage, LdapState.LdapConnectionError));
                return LdapState.LdapConnectionError;
            }

            var successConnectionMessage = String.Format("Connection success\n User: {0}\n Pwd: {1}{2}{3}{4}",
                credential.UserName,
                credential.Password,
                (_configRepository.GetSecureSocketLayerFlag() ? "\n With SSL " : ""),
                (_configRepository.GetTransportSocketLayerFlag() ? "\n With TLS " : ""),
                (_configRepository.GetClientCertificateFlag() ? "\n With Client Certificate" : ""));
            if (_adminModeChecker.IsNoAdminMode())
                _ldapConnection.Dispose();
            _logger.Write(_logger.BuildLogMessage(successConnectionMessage, LdapState.LdapConnectionSuccess));
            return LdapState.LdapConnectionSuccess;
        }
开发者ID:barrett2474,项目名称:CMS2,代码行数:32,代码来源:LdapConnector.cs

示例9: getAccountAttributeDN

        /// <summary>
        /// This method is used to get attribute display name of an account
        /// </summary>
        /// <param name="domainName">Local domain Name</param>
        /// <param name="accountName">Account name, user name or computer name</param>
        /// <param name="accountType">Users or computers</param>
        /// <param name="attributename">The attribute of account to query</param>
        /// <param name="adminName">Admin user Name</param>
        /// <param name="adminPwd">Admin password</param>
        public string getAccountAttributeDN(string domainName, string accountName, string accountType, string attributeName, string adminName, string adminPwd)
        {
            LdapConnection connection = new LdapConnection(domainName);
            NetworkCredential cred = new NetworkCredential(adminName, adminPwd, domainName);
            connection.Credential = cred;
            string dn = PacHelper.GetDomainDnFromDomainName(domainName);
            string targetOu = "CN=" + accountName + ",CN=" + accountType + ",DC=" + domainName + ",DC=com";

            string filter = "CN=" + accountName;
            string[] attributesToReturn = new string[] { attributeName };

            SearchRequest searchRequest = null;
            SearchResponse searchResponse = null;
            string attributeValue = null;

            try
            {
                searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);

                searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                object attribute = null;
                attribute = PacHelper.getAttributeValue(attributes, attributeName);
                attributeValue = Convert.ToString(attribute);

            }
            catch
            {
                throw new InvalidOperationException("Request attribute failed with targetOU: " + targetOu + ", filter: " + filter + ", attribute: " + attributeName);
            }

            return attributeValue;
        }
开发者ID:yazeng,项目名称:WindowsProtocolTestSuites,代码行数:42,代码来源:SutControlAdapter.cs

示例10: Client

        public Client(string username, string domain, string password, string url)
        {
            var credentials = new NetworkCredential(username, password, domain);
            var serverId = new LdapDirectoryIdentifier(url);

            connection = new LdapConnection(serverId, credentials);
            connection.Bind();      
        }
开发者ID:mehreencs87,项目名称:blog-ldap-csharp-example,代码行数:8,代码来源:Client.cs

示例11: StandardConnect

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        protected void StandardConnect(NetworkCredential credential)
        {
            if (LdapParameterChecker.ParametersIsNullOrEmpty(new []{credential.UserName})) throw new InvalidCredentialException("Username cannot be null or empty");
            if (LdapParameterChecker.ParametersIsNullOrEmpty(new []{credential.Password})) throw new InvalidCredentialException("Password cannot be null or empty");

            _ldapConnection = LdapConnectionFactory.GetLdapConnection(_configRepository);
            _ldapConnection.Bind(credential);
        }
开发者ID:tu226,项目名称:LDAP-Library,代码行数:10,代码来源:ALdapConnector.cs

示例12: LdapSessionOptions

 internal LdapSessionOptions(LdapConnection connection)
 {
     this.connection = connection;
     this.queryDelegate = new QUERYFORCONNECTIONInternal(this.ProcessQueryConnection);
     this.notifiyDelegate = new NOTIFYOFNEWCONNECTIONInternal(this.ProcessNotifyConnection);
     this.dereferenceDelegate = new DEREFERENCECONNECTIONInternal(this.ProcessDereferenceConnection);
     this.serverCertificateRoutine = new VERIFYSERVERCERT(this.ProcessServerCertificate);
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:LdapSessionOptions.cs

示例13: ConnectLDAP

 public bool ConnectLDAP()
 {
     m_LdapConnection = new LdapConnection(m_LdapServer);
     m_LdapConnection.SessionOptions.ProtocolVersion = 3;
     m_LdapConnection.AuthType = AuthType.Basic;
     m_LdapConnection.Credential = m_Credential;
     m_LdapConnection.Bind();
     return true;
 }
开发者ID:huaminglee,项目名称:Code,代码行数:9,代码来源:LdapConnect.cs

示例14: LdapPartialAsyncResult

 public LdapPartialAsyncResult(int messageID, AsyncCallback callbackRoutine, object state, bool partialResults, LdapConnection con, bool partialCallback, TimeSpan requestTimeout) : base(callbackRoutine, state, partialResults)
 {
     this.messageID = -1;
     this.messageID = messageID;
     this.con = con;
     base.partialResults = true;
     this.partialCallback = partialCallback;
     this.requestTimeout = requestTimeout;
     this.startTime = DateTime.Now;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:10,代码来源:LdapPartialAsyncResult.cs

示例15: Main

        static void Main(string[] args)
        {
            // LdapTest <address> <domain> [<username> <password> [<domain>]]
              //              0        1          2          3           4
              var directory = new LdapDirectoryIdentifier(args[0]);
              var credential = args.Length > 4 ? new NetworkCredential(args[2], args[3], args[4])
            : args.Length > 2 ? new NetworkCredential(args[2], args[3])
            : new NetworkCredential();

              using (var connection = new LdapConnection(directory, credential))
              {
            //while (true)
            {
              var request = new SearchRequest(
            "DC=" + args[1].Replace(".", ",DC="),
            "(&(objectClass=organizationalPerson)(sAMAccountType=805306368))",
            System.DirectoryServices.Protocols.SearchScope.Subtree,
            new[] { "cn" }
              );

              try
              {
            var t = Stopwatch.StartNew();

            PageResultRequestControl pageRequestControl = new PageResultRequestControl(1000);

            // used to retrieve the cookie to send for the subsequent request
            PageResultResponseControl pageResponseControl;
            request.Controls.Add(pageRequestControl);

            while (true)
            {
              var response = (SearchResponse)connection.SendRequest(request);
              pageResponseControl = (PageResultResponseControl)response.Controls[0];
              if (pageResponseControl.Cookie.Length == 0)
                break;
              pageRequestControl.Cookie = pageResponseControl.Cookie;
              Console.WriteLine("{0}\t{1} entries: {2} - {3} in {4:F1}", DateTime.Now, response.Entries.Count,
                AttributeOf(response.Entries[0], "cn"),
                AttributeOf(response.Entries[response.Entries.Count - 1], "cn"),
                t.Elapsed.TotalSeconds
              );
            }
            t.Stop();
              }
              catch (Exception ex)
              {
            Console.WriteLine("{0}\tERRROR - {1}", DateTime.Now, ex.Message);
              }
              //Thread.Sleep(TimeSpan.FromSeconds(30));
            }
              }
        }
开发者ID:stormcrow79,项目名称:FrameworkTests,代码行数:53,代码来源:Program.cs


注:本文中的System.DirectoryServices.Protocols.LdapConnection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。