예제 #1
0
        /// <summary>
        /// Método que se encarga de obtener el nombre de una persona a partir de su nombre de usuario (login)
        /// </summary>
        /// <param name="nombreUsuario">Nombre de usuario (login)</param>
        /// <returns>Nombre de la persona</returns>

        public String obtenerNombrePersona(string nombreUsuario)
        {
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            try
            {
                String nombrePersona;
                // Crear conexion con LDAP
                openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
                openLdap.AuthType   = AuthType.Basic;
                openLdap.SessionOptions.ProtocolVersion = 3;                  // Hay que usar LDAPv3
                openLdap.Bind();                                              //Conectar
                string[] attributesToReturn = new string[] { "displayName" }; // Atributos a retornar
                // Buscar al usuario por su login
                SearchRequest searchRequest = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + nombreUsuario + "*)",
                                                                System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn);
                SearchResponse     searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);             // Respuesta del servidor
                DirectoryAttribute atributo       = searchResponse.Entries[0].Attributes["displayName"];
                object[]           objeto         = atributo.GetValues(Type.GetType("System.Byte[]"));
                nombrePersona = Encoding.ASCII.GetString((byte[])objeto[0]);
                openLdap.Dispose();                 // Liberar recursos
                return(nombrePersona);
            }
            catch (Exception e)
            {
                openLdap.Dispose();
                _conexionBD = new ManejoBD();
                _conexionBD.insertarBitacoraError(e.ToString(), "");
                return(null);
            }
        }
예제 #2
0
        public void Dispose_MultipleTimes_Nop()
        {
            var connection = new LdapConnection("server");

            connection.Dispose();
            connection.Dispose();
        }
예제 #3
0
        public void ReleaseConnection(LdapConnection connection)
        {
            var lockObject = _connectionLockObject;

            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (lockObject == null)
            {
                //lock is null so this class is being finalized
                connection.Dispose();
                _inUseConnections?.Remove(connection);
                if (Logger != null && Logger.TraceEnabled)
                {
                    Logger.Trace("Synchronization object lost. Disposing of connection.");
                }
                return;
            }

            lock (lockObject)
            {
                DateTime createdDate;
                if (_inUseConnections.TryGetValue(connection, out createdDate))
                {
                    _inUseConnections.Remove(connection);
                    if (DateTime.Now.Subtract(createdDate).TotalMinutes < _maxConnectionAge.TotalMinutes)
                    {
                        _availableConnections.Add(connection, new TwoTuple <DateTime, DateTime>(createdDate, DateTime.Now));
                        if (Logger != null && Logger.TraceEnabled)
                        {
                            Logger.Trace("Connection Marked As Available");
                        }
                    }
                    else
                    {
                        connection.Dispose();
                        if (Logger != null && Logger.TraceEnabled)
                        {
                            Logger.Trace("Connection Exceeds Max Age. Connection Disposed.");
                        }
                    }
                }
                else
                {
                    connection.Dispose();
                    if (Logger != null && Logger.TraceEnabled)
                    {
                        Logger.Trace("Connection Disposed");
                    }
                }
            }
        }
예제 #4
0
        public void Login(string userAccount, string password)
        {
            // 若之前有登入過,則先釋放資源。
            if (_connection != null)
            {
                _connection.Dispose();
            }

            _connection            = new LdapConnection(_serverUrl);
            _connection.Credential = new NetworkCredential(userAccount, password); // 雖然有個多型可以傳入 Domain 但是沒有效果。
            _connection.Bind();                                                    // 登入
        }
        public bool CheckCredentialServer(LdapServiceModel ldapServiceModel)
        {
            bool success = false;

            _ldapServer = ldapServiceModel.ldapServer;
            _ldapPort   = ldapServiceModel.ldapPort;
            LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(_ldapServer, Convert.ToInt16(_ldapPort), true, false);
            LdapConnection          ldapConnection          = new LdapConnection(ldapDirectoryIdentifier);

            try
            {
                ldapConnection.AuthType = AuthType.Anonymous;
                ldapConnection.AutoBind = false;
                ldapConnection.Timeout  = new TimeSpan(0, 0, 0, 1);
                ldapConnection.Bind();
                ldapConnection.Dispose();
                success = true;
            }
            catch (LdapException)
            {
                success = false;
            }

            return(success);
        }
예제 #6
0
 public void ReleaseConnection(LdapConnection connection)
 {
     if (_disposed)
     {
         throw new ObjectDisposedException(GetType().FullName);
     }
     lock (_connectionLockObject)
     {
         if (_inUseConnections.Remove(connection))
         {
             _availableConnections.Add(connection, DateTime.Now);
             if (Logger != null && Logger.TraceEnabled)
             {
                 Logger.Trace("Connection Marked As Available");
             }
         }
         else
         {
             connection.Dispose();
             if (Logger != null && Logger.TraceEnabled)
             {
                 Logger.Trace("Connection Disposed");
             }
         }
     }
 }
예제 #7
0
        public bool DoAuthentication(string Domain, string User, string Password)
        {
            try
            {
                // Create the new LDAP connection
                LdapDirectoryIdentifier ldi            = new LdapDirectoryIdentifier(Domain, 389);
                LdapConnection          ldapConnection = new LdapConnection(ldi);
                Console.WriteLine("LdapConnection is created successfully.");
                ldapConnection.AuthType = AuthType.Basic;
                ldapConnection.SessionOptions.ProtocolVersion = 3;

                NetworkCredential nc = new NetworkCredential(User + "@" + Domain, Password); //password
                ldapConnection.Bind(nc);
                Console.WriteLine("LdapConnection authentication success");
                ldapConnection.Dispose();
                return(true);
            }
            catch (LdapException e)
            {
                Console.WriteLine("\r\nUnable to login:\r\n\t" + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() + ":" + e.Message);
            }

            return(false);
        }
        public static bool IsAuthenticated(string username, string password, string domain)
        {
            bool authenticated = false;

            //pass the connectionString here
            using (LdapConnection connection = new LdapConnection(connectionString))
            {
                try
                {
                    username            = username + domain;
                    connection.AuthType = AuthType.Basic;
                    connection.SessionOptions.ProtocolVersion = 3;
                    var credential = new NetworkCredential(username, password);
                    connection.Bind(credential);
                    authenticated = true;
                    return(authenticated);
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.Message);
                    return(authenticated);
                }
                finally
                {
                    connection.Dispose();
                }
            }
        }
        //~~~~~~~~~~~~~~~~~~~~~~Disposable~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        /// <summary>
        /// Purge the connection and the object reference in the class
        /// </summary>
        public void Dispose()
        {
            _configRepository = null;
            _logger           = null;
            _observers        = null;
            _ldapConnection.Dispose();
        }
예제 #10
0
        public void Dispose()
        {
            if (!IsConnected)
            {
                return;
            }

            try
            {
                _ldapConnection.Constraints.TimeLimit             = 10000;
                _ldapConnection.SearchConstraints.ServerTimeLimit = 10000;
                _ldapConnection.SearchConstraints.TimeLimit       = 10000;
                _ldapConnection.ConnectionTimeout = 10000;

                if (_ldapConnection.TLS)
                {
                    _log.Debug("ldapConnection.StopTls();");
                    _ldapConnection.StopTls();
                }

                _log.Debug("ldapConnection.Disconnect();");
                _ldapConnection.Disconnect();

                _log.Debug("ldapConnection.Dispose();");
                _ldapConnection.Dispose();

                _ldapConnection = null;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("LDAP->Dispose() failed. Error: {0}", ex);
            }
        }
예제 #11
0
        bool IsLdapOk()
        {
            string ldapServer = form.domainField;
            // This function requires Imports System.Net and Imports System.DirectoryServices.Protocols
            LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(ldapServer));
            //Specify LDAP timeout
            TimeSpan mytimeout = new TimeSpan(0, 0, 1);
            bool     ldapOK    = false;

            try
            {
                //ldapConnection.AuthType = AuthType.Negotiate;
                //ldapConnection.AutoBind = false;
                ldapConnection.Timeout = mytimeout;
                ldapConnection.Bind();
                form.OUTextBox = "Successfully authenticated to LDAP server " + ldapServer;
                ldapOK         = true;
                ldapConnection.Dispose();
            }
            catch (LdapException e)
            {
                form.OUTextBox = "Looks like I couldn't reach the LDAP server: " + ldapServer + "\n" + e.Message;
                ldapOK         = false;
            }
            return(ldapOK);
        }
예제 #12
0
        public static LdapSearchResponse GetDomainInfo(string server, string domain, NetworkCredential credential)
        {
            string             rootNc   = "DC=" + domain.Replace(".", ",DC=");
            LdapSearchResponse pingrep  = new LdapSearchResponse();
            LdapConnection     ldapconn = new LdapConnection(server);

            ldapconn.Bind(credential);
            SearchRequest  sr = new SearchRequest(rootNc, "(objectClass=*)", SearchScope.Base);
            SearchResponse sp = ldapconn.SendRequest(sr) as SearchResponse;

            if (sp.ResultCode != ResultCode.Success)
            {
                throw new AutoDetectionException(string.Format("Cannot get information of domain: {0} from server {1}.", domain, server));
            }
            var attributes = sp.Entries[0].Attributes;

            // Domain GUID
            byte[] rawguid = attributes["objectGuid"][0] as byte[];
            pingrep.DomainGuid = (new Guid(rawguid)).ToString().ToUpper();

            // Domain SID
            byte[] rawsid = attributes["objectSid"][0] as byte[];
            pingrep.DomainSid = (new System.Security.Principal.SecurityIdentifier(rawsid, 0)).ToString().ToUpper();
            ldapconn.Dispose();
            return(pingrep);
        }
예제 #13
0
        public bool IsValidADUser(string username, string password)
        {
            bool userValidationFlag = true;
            var  credential         = new NetworkCredential(username, password);
            var  serverId           = new LdapDirectoryIdentifier(LDAP_SERVER);
            var  conn = new LdapConnection(serverId, credential);

            try
            {
                conn.Bind();
            }
            catch (Exception)
            {
                userValidationFlag = false;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }

            return(userValidationFlag);
        }
예제 #14
0
            //public string CreateEntry(INovellOrganizationContactPerson person)
            //{
            //    string DN = "";
            //    string containerName = "ou=users,o=alien";
            //    try
            //    {
            //        string dn = "cn=" + person.Login + "," + containerName;
            //        string dirClassType = "inetOrgPerson";
            //        AddRequest addRequest = new AddRequest(dn, dirClassType);
            //        addRequest.Attributes.Add(new DirectoryAttribute("cn", new string[] { person.Login }));
            //        addRequest.Attributes.Add(new DirectoryAttribute("givenname", person.FirstName));
            //        addRequest.Attributes.Add(new DirectoryAttribute("sn", person.Surname));
            //        addRequest.Attributes.Add(new DirectoryAttribute("mail", person.Email));
            //        addRequest.Attributes.Add(new DirectoryAttribute("userpassword", person.Password));
            //        AddResponse addResponse = (AddResponse)Connection.SendRequest(addRequest);
            //        DN = dn;
            //    }
            //    catch (Exception e)
            //    {
            //        Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
            //                          e.GetType().Name, e.Message);
            //    }
            //    return DN;
            //}

            //private bool CheckPassword(string login, string password, string basedn)
            //{
            //    bool correct = false;

            //    string ldapserver = ServerAddress.ToString() + ":636";
            //    string ldapbasedn = "o=" + basedn;
            //    string ldapuser = "******";
            //    string ldappassword = "******";
            //    string ldapfilter = "(&(cn={0}))";
            //    try
            //    {
            //        string DN = "";
            //        using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapserver + "/" + ldapbasedn, ldapuser, ldappassword, AuthenticationTypes.None))
            //        {
            //            DirectorySearcher ds = new DirectorySearcher(entry);
            //            ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            //            ds.Filter = string.Format(ldapfilter, login);
            //            SearchResult result = ds.FindOne();
            //            if (result != null)
            //            {
            //                DN = result.Path.Replace("LDAP://" + ldapserver + "/", "");
            //            }
            //        }
            //        if (DN != null && DN != "")
            //        {
            //            using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapserver + "/" + ldapbasedn, DN, password, AuthenticationTypes.None))
            //            {
            //                DirectorySearcher ds = new DirectorySearcher(entry);
            //                ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            //                SearchResult result = ds.FindOne();
            //                if (result != null)
            //                {
            //                    correct = true;
            //                }
            //            }
            //        }
            //        else
            //        {
            //            correct = false;
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        correct = false;
            //    }
            //    return correct;
            //}

            public void Dispose()
            {
                if (connection != null)
                {
                    connection.Dispose();
                }
            }
예제 #15
0
        public LDAP(LdapDirectoryIdentifier inConn)
        {
            LDI              = inConn;
            theConn          = new LdapConnection(inConn);
            theConn.AuthType = AuthType.Anonymous; //anon needed to get rootDSE

            theConn.Timeout = new TimeSpan(0, 15, 0);
            getRootDSEData();

            //switch to an auth'd context
            theConn.Dispose();
            theConn = new LdapConnection(inConn);
            //add creds

            theConn.AuthType = AuthType.Negotiate;
            theConn.SessionOptions.RootDseCache = true;
            theConn.Timeout = new TimeSpan(0, 15, 0);
            theConn.SessionOptions.SendTimeout     = new TimeSpan(0, 15, 0);
            theConn.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
            theConn.SessionOptions.Signing         = true;
            theConn.SessionOptions.Sealing         = true; //the key to getting back password blobs and encryption...
            try
            {
                theConn.Bind();
            }
            catch (Exception ex)
            {
                throw new Exception("LDAP Test Bind failed", ex);
            }
        }
예제 #16
0
        public SearchResultEntryCollection Load(string container, string filter)
        {
            LdapConnection conn = null;

            try
            {
                conn = GetConnection();

                SearchRequest sr = new SearchRequest();
                sr.DistinguishedName = container;
                sr.Scope             = System.DirectoryServices.Protocols.SearchScope.OneLevel;
                sr.Filter            = filter;

                conn.Bind();
                SearchResponse resp = (SearchResponse)conn.SendRequest(sr);

                return(resp.Entries);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }
        }
예제 #17
0
        public void UpdateDN(string uniqueName, string originalName)
        {
            if (uniqueName == originalName)
            {
                return;
            }

            ModifyDNRequest mdr = new ModifyDNRequest();

            mdr.DistinguishedName = originalName;
            mdr.NewName           = uniqueName;

            using (LdapConnection conn = GetConnection())
                try
                {
                    conn.SendRequest(mdr);
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Dispose();
                    }
                }
        }
        private Boolean IsAuthenticated(string username, string password, string domain)
        {
            Boolean authenticated = false;

            using (LdapConnection connection = new LdapConnection(domain))
            {
                try
                {
                    username            = username + "@" + domain;
                    connection.AuthType = AuthType.Basic;
                    connection.SessionOptions.ProtocolVersion = 3;
                    var credential = new NetworkCredential(username, password);
                    connection.Bind(credential);
                    authenticated = true;
                    return(authenticated);
                }
                catch (LdapException)
                {
                    return(authenticated);
                }
                finally
                {
                    connection.Dispose();
                }
            }
        }
예제 #19
0
        //protected void btnWordToPdf_Click(object sender, EventArgs e)
        //{
        //    if (WordToPDF(Server.MapPath("/upload/2.docx"), Server.MapPath("/upload/2.pdf")))
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "temp", "alert('转换成功');", true);
        //        return;
        //    }
        //    else
        //    {
        //        ClientScript.RegisterStartupScript(this.GetType(), "temp", "alert('转换失败');", true);
        //        return;
        //    }
        //}
        //public string PreviewWord(string physicalPath, string url)
        //{
        //    Microsoft.Office.Interop.Word._Application application = null;
        //    Microsoft.Office.Interop.Word._Document doc = null;
        //    application = new Microsoft.Office.Interop.Word.Application();
        //    object missing = Type.Missing;
        //    object trueObject = true;
        //    application.Visible = false;
        //    application.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
        //    doc = application.Documents.Open(physicalPath, missing, trueObject, missing, missing, missing,
        //      missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
        //    //Save Excel to Html
        //    object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
        //    string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
        //    String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
        //    doc.SaveAs(outputFile, format, missing, missing, missing,
        //             missing, missing, missing,
        //             missing, missing, missing, missing);
        //    doc.Close();
        //    application.Quit();
        //    return Path.GetDirectoryName(Server.UrlDecode(url)) + "\\" + htmlName;
        //}
        //public bool WordToPDF(string sourcePath, string targetPath)
        //{
        //    bool result = false;
        //    Microsoft.Office.Interop.Word._Application application = new Microsoft.Office.Interop.Word.Application();
        //    Microsoft.Office.Interop.Word._Document document = null;
        //    try
        //    {
        //        application.Visible = false;
        //        document = application.Documents.Open(sourcePath);
        //        document.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
        //        result = true;
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e.Message);
        //        result = false;
        //    }
        //    finally
        //    {
        //        document.Close();
        //    }
        //    return result;
        //}

        private void CheckSchoolUser(string portal, string password)
        {
            String LDAP_Server               = "ca.zucc.edu.cn";
            int    LDAP_Port                 = 389;
            String LDAP_Search_DN            = "ou=people,dc=zucc,dc=edu,dc=cn";
            LdapDirectoryIdentifier ldapDir  = new LdapDirectoryIdentifier(LDAP_Server, LDAP_Port);
            LdapConnection          ldapConn = new LdapConnection(ldapDir);

            ldapConn.AuthType = AuthType.Basic;
            //portal是用户名,11111111是密码
            System.Net.NetworkCredential myCredentials = new System.Net.NetworkCredential("uid=" + portal + "," + LDAP_Search_DN, password);
            try
            {
                ldapConn.Bind(myCredentials);
            }
            catch (LdapException e1)
            {
                Console.WriteLine("Exception in auth with LDAP Server:" + e1.Message);
                Response.Write("Auth failed!");
                return;
            }
            finally
            {
                if (ldapConn != null)
                {
                    ldapConn.Dispose();
                }
            }
            Response.Write("Auth successful!");
        }
예제 #20
0
        private string GetUserDistinguishedName(string username)
        {
            LdapConnection ldap = null;

            try
            {
                ldap = GetLdapConnection(LdapUsername, LdapPassword);

                if (ldap == null)
                {
                    return(null);
                }

                SearchResultEntry sre = GetUserSearchResultEntry(ldap, username);
                if (sre != null)
                {
                    return(sre.DistinguishedName);
                }
            }
            finally
            {
                if (ldap != null)
                {
                    ldap.Dispose();
                    ldap = null;
                }
            }

            return(null);
        }
예제 #21
0
 public static bool Bind(string username, string password)
 {
     if (password.Length > 0)
     {
         try
         {
             LdapDirectoryIdentifier LDAPdi         = new LdapDirectoryIdentifier("ldap.pmhu.local", 389);
             LdapConnection          ldapConnection = new LdapConnection(LDAPdi);
             ldapConnection.AuthType = AuthType.Basic;
             ldapConnection.SessionOptions.ProtocolVersion = 3;
             NetworkCredential networkCredential = new NetworkCredential(username + "@pmhu.local", password);
             ldapConnection.Bind(networkCredential);
             ldapConnection.Dispose();
             return(true);
         }
         catch (LdapException e)
         {
             Console.WriteLine("\r\nUnable to login:\r\n\t" + e.Message);
         }
         catch (Exception e)
         {
             Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() + ":" + e.Message);
         }
     }
     return(false);
 }
예제 #22
0
        private bool AuthenticateUser(string userDistinguishedName, string password)
        {
            LdapConnection ldap = null;

            try
            {
                // authenticate user by binding to the userDistinguishedName with user provided password
                ldap = GetLdapConnection(userDistinguishedName, password);

                return(ldap != null);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            finally
            {
                if (ldap != null)
                {
                    ldap.Dispose();
                    ldap = null;
                }
            }

            return(false);
        }
예제 #23
0
        public static void LdapBind(string server, NetworkCredential credential)
        {
            LdapConnection ldapconn = new LdapConnection(server);

            ldapconn.Bind(credential);
            ldapconn.Dispose();
        }
예제 #24
0
        /// <summary>
        /// Método que busca el login de un usuario basado en su numero de carné
        /// </summary>
        /// <param name="carne">Numero de carné</param>
        /// <returns>Login del usuario correspondiente al carné</returns>

        public String buscarUsuarioPorCarnet(string carne)
        {
            string uid = "";
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
            openLdap.AuthType   = AuthType.Basic;
            openLdap.SessionOptions.ProtocolVersion = 3;                                                                                      // Hay que usar LDAPv3
            openLdap.Bind();                                                                                                                  // Conectar

            string[]      attributesToReturn = new string[] { "uid" };                                                                        // Retornar solamente el login
            SearchRequest searchRequest      = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(gecos=" + carne + "*)",
                                                                 System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar por carnet
            SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);                                              // Respuesta del servidor

            if (searchResponse.Entries.Count != 0)
            {
                DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["uid"];
                object[]           objeto   = atributo.GetValues(Type.GetType("System.Byte[]"));
                uid = Encoding.ASCII.GetString((byte[])objeto[0]);
            }
            openLdap.Dispose();             // Liberar recursos
            return(uid);
        }
예제 #25
0
        // Need to check on Linux OS
        public static bool IsAuthenticated(string username, string password)
        {
            bool authenticated = false;

            using (LdapConnection connection = new LdapConnection(LDAP_PATH))
            {
                try
                {
                    username           += LDAP_DOMAIN;
                    connection.AuthType = AuthType.Basic;
                    connection.SessionOptions.ProtocolVersion = 3;
                    var credential = new NetworkCredential(username, password);
                    connection.Bind(credential);
                    authenticated = true;
                    return(authenticated);
                }
                catch (LdapException)
                {
                    return(authenticated);
                }
                finally
                {
                    connection.Dispose();
                }
            }
        }
 private void Unbind()
 {
     _ldapConnection?.Dispose();
     _ldapConnection            = null;
     _distinguishedName         = null;
     _relativeDistinguishedName = null;
 }
예제 #27
0
        /// <summary>
        /// Método que retorna el proximo identificador unico libre
        /// </summary>
        /// <returns>Identificador único libre</returns>

        private String obtenerNumeroUid()
        {
            string uid = "";
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
            openLdap.AuthType   = AuthType.Basic;
            openLdap.SessionOptions.ProtocolVersion = 3;                                                                                      // Hay que usar LDAPv3
            openLdap.Bind();                                                                                                                  // Conectar
            string[]      attributesToReturn = new string[] { "uidNumber" };                                                                  // Retornar solamente el uid number
            SearchRequest searchRequest      = new SearchRequest("dc=ic-itcr,dc=ac,dc=cr", "(cn=NextFreeUnixId)",
                                                                 System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar al objeto NextFreeUnixId
            SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);                                              // Respuesta del servidor
            // Manejar la respuesta
            DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["uidNumber"];

            object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
            uid = Encoding.ASCII.GetString((byte[])objeto[0]);
            int           siguienteuid = Int32.Parse(uid) + 1;                                                                           // Actualizar el Unix Id libre
            ModifyRequest incremento   = new ModifyRequest("cn=NextFreeUnixId,dc=ic-itcr,dc=ac,dc=cr"
                                                           , DirectoryAttributeOperation.Replace, "uidNumber", siguienteuid.ToString()); // Modificar el NextFreeUnixId en el servidor

            openLdap.SendRequest(incremento);
            openLdap.Dispose();
            return(uid);            // Retornar el uid
        }
예제 #28
0
        public static bool Authenticated(string username, string password, string domain = "gsb")
        {
            bool isSuccess;

            try
            {
                var ldi = new LdapDirectoryIdentifier(Server, Port);

                var lc = new LdapConnection(ldi);
                var nc = new NetworkCredential(username, password, domain + ".local");

                lc.Bind(nc);

                isSuccess = true;

                lc.Dispose();
            }
            catch (LdapException)
            {
                isSuccess = false;
                // throw new LdapException(e.ErrorCode, e.Message, e.InnerException);
            }
            catch (Exception)
            {
                isSuccess = false;
                // throw new Exception();
            }

            return(isSuccess);
        }
예제 #29
0
        public void Abort_Disposed_ThrowsObjectDisposedException()
        {
            var connection = new LdapConnection("server");

            connection.Dispose();

            Assert.Throws <ObjectDisposedException>(() => connection.Abort(null));
        }
예제 #30
0
        public void GetPartialResults_Disposed_ThrowsObjectDisposedException()
        {
            var connection = new LdapConnection("server");

            connection.Dispose();

            Assert.Throws <ObjectDisposedException>(() => connection.GetPartialResults(null));
        }