/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="filter"></param> /// <param name="attributes"></param> /// <returns></returns> private List <LdapEntry> ForLdapEntries(string key, string value, string filter, string[] attributes) { List <LdapEntry> searchResults = new List <LdapEntry>(); using (LdapConnection conn = new LdapConnection()) { conn.Connect(_config.Host, _config.LDAPPort); conn.Bind(_config.LDAPVersion, _config.UserName, _config.Password); LdapSearchResults results = conn.Search(_config.Container, //search base LdapConnection.SCOPE_SUB, //scope filter, //filter attributes, //attributes false); //types only while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); if (nextEntry != null) { searchResults.Add(nextEntry); } } catch (LdapException) { continue; } } } return(searchResults); }
/// <summary> /// Find user by name /// </summary> /// <param name="userName">User name</param> /// <returns>LdapEntry object</returns> /// <see cref="https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bow8dju.html"/> public async Task <LdapEntry> FindAsync(string userName) { Func <LdapConnection, LdapEntry> action = (ldapConn) => { // Set search filter var searchFilter = $"(cn={userName})"; // Get search result LdapSearchResults searchResults = ldapConn.Search( this.ldapServer.SearchBase, scope: LdapConnection.SCOPE_SUB, filter: searchFilter, // Search filter attrs: new string[] { "cn", "displayName", "mail" }, // The attributes to retrieve typesOnly: false); // Note in Novell.Directory.Ldap.NETStandard >=3.0.1, LdapSearchResults implement IEnumerable... // return searchResults.AsEnumerable().FirstOrDefault(); while (searchResults.hasMore()) { var entry = searchResults.next(); return(entry); } return(default(LdapEntry)); }; return(await this.ldapActionAsync(action)); }
public void Ldap_Search_Should_Return_Correct_Results_Count() { var loginDN = "dc=example,dc=com"; var password = ""; LdapConnection conn = new LdapConnection(); conn.Connect(Globals.Host, Globals.DefaultPort); conn.Bind(loginDN, password); LdapSearchResults lsc = conn.Search( "dc=example,dc=com", LdapConnection.SCOPE_SUB, "objectclass=*", null, false); int resultsCount = lsc.Count; int counter = 0; while (lsc.hasMore()) { LdapEntry nextEntry = lsc.next(); ++counter; } Assert.Equal(resultsCount, counter); conn.Disconnect(); }
public static bool searchGroupEntry(LdapConnection lc, String searchBase, string searchFilter) { bool status = true; int searchScope = LdapConnection.SCOPE_SUB; String[] attrList = new String[] { "distinguishedName" }; LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; try { LdapSearchResults searchResults = lc.Search(searchBase, searchScope, searchFilter, attrList, false, cons); // time out value LdapEntry nextEntry = null; if ((nextEntry = searchResults.next()) == null) { status = false; } } catch { status = false; } return(status); }
public static void Main(String[] args) { int LdapPort = 10389; int searchScope = LdapConnection.SCOPE_ONE; int LdapVersion = LdapConnection.Ldap_V3;; bool attributeOnly = true; String[] attrs = { LdapConnection.NO_ATTRS }; String ldapHost = "192.168.2.130"; String loginDN = ""; String password = ""; String searchBase = ""; String searchFilter = ""; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect(ldapHost, LdapPort); // bind to the server lc.Bind(LdapVersion, loginDN, password); LdapSearchResults searchResults = lc.Search(searchBase, // container to search searchScope, // search scope searchFilter, // search filter attrs, // "1.1" returns entry name only attributeOnly); // no attributes are returned // print out all the objects while (searchResults.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = searchResults.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); } // disconnect with the server lc.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
public sbyte[] GetLdapInfo(string num, string attr) { string filter = string.Format("telephoneNumber={0}", num); LdapConnection conn = GetConnection(); LdapSearchResults result = conn.Search("dc=renstech,dc=com", LdapConnection.SCOPE_SUB, filter, null, false); while (result.hasMore()) { LdapEntry nextEntry; try { nextEntry = result.next(); } catch (LdapException) { continue; } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (attributeName == attr) { return(attribute.ByteValue); } //string attributeVal = attribute.StringValue; } } return(null); }
public IEnumerator GetEnumerator() { m_oValues = new ArrayList(); string[] attrs = { "objectClass" }; LdapSearchResults lsc = Conn.Search(Basedn, LdapConnection.SCOPE_ONE, "objectClass=*", attrs, false); LdapUrl Burl = new LdapUrl(_Bpath); string host = Burl.Host; int port = Burl.Port; while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { // Exception is thrown, go for next entry continue; } DirectoryEntry dEntry = new DirectoryEntry(Conn); string eFdn = nextEntry.DN; LdapUrl curl = new LdapUrl(host, port, eFdn); dEntry.Path = curl.ToString(); m_oValues.Add((DirectoryEntry)dEntry); } return(m_oValues.GetEnumerator()); }
ADInfo Search(LdapConnection ldapConn) { LdapSearchConstraints constraints = new LdapSearchConstraints { TimeLimit = 10000 }; LdapSearchResults lsc = ldapConn.Search( SearchBase, LdapConnection.SCOPE_SUB, "SAMAccountName=" + Username.ToLower(), null, // no specified attributes false, // return attr and value constraints); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); return(new ADInfo(Username, nextEntry)); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } } return(null); }
/// <summary> /// Loads the values of the specified properties into the property cache. /// </summary> /// <param name="propertyNames">An array of the specified properties.</param> private void LoadProperties(PropertyCollection properties, string[] propertyNames) { _inPropertiesLoading = true; try { LdapSearchResults lsc = conn.Search(Fdn, LdapConnection.SCOPE_BASE, "objectClass=*", propertyNames, false); if (lsc.hasMore()) { LdapEntry nextEntry = lsc.next(); string [] lowcasePropertyNames = null; int length = 0; if (propertyNames != null) { length = propertyNames.Length; lowcasePropertyNames = new string [length]; for (int i = 0; i < length; i++) { lowcasePropertyNames [i] = propertyNames [i].ToLower(); } } foreach (LdapAttribute attribute in nextEntry.getAttributeSet()) { string attributeName = attribute.Name; if ((propertyNames == null) || (Array.IndexOf(lowcasePropertyNames, attributeName.ToLower()) != -1)) { properties [attributeName].Value = null; properties [attributeName].AddRange(attribute.StringValueArray); properties [attributeName].Mbit = false; } } } } finally { _inPropertiesLoading = false; } }
/// <summary> /// Finds ldap entry /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="filter">The ADO query filter</param> /// <param name="attributes">Properties to load</param> /// <returns></returns> private LdapEntry ForLdapEntry(string key, string value, string filter, string[] attributes) { LdapEntry searchResult = null; using (LdapConnection conn = new LdapConnection()) { conn.Connect(_config.Host, _config.LDAPPort); conn.Bind(_config.LDAPVersion, _config.UserName, _config.Password); //Search LdapSearchResults results = conn.Search(_config.Container, //search base LdapConnection.SCOPE_SUB, //scope filter, //filter attributes, //attributes false); //types only while (results.hasMore()) { try { searchResult = results.next(); break; } catch (LdapException e) { throw e; } } } return(searchResult); }
/// <summary> /// Searches an entry in the Ldap directory and returns the attribute value /// </summary> /// <param name="attrName">attribute whose value is required</param> /// <returns> value of the attribute stored in Ldap directory</returns> private string FindAttrValue(string attrName) { string aValue = null; string[] attrs = { attrName }; LdapSearchResults lsc = conn.Search(Fdn, LdapConnection.SCOPE_BASE, "objectClass=*", attrs, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { // Exception is thrown, go for next entry throw e; } LdapAttribute attribute = nextEntry.getAttribute(attrName); aValue = attribute.StringValue; break; } return(aValue); }
private List <LdapEntry> Search(string login, string password, string server, int portNumber, bool startTls, int scope, string searchFilter = null, string disnguishedName = null, string[] attributes = null) { if (server.StartsWith("LDAP://")) { server = server.Substring("LDAP://".Length); } var entries = new List <LdapEntry>(); var ldapConnection = new LdapConnection(); if (startTls) { ldapConnection.UserDefinedServerCertValidationDelegate += TlsHandler; } ldapConnection.Connect(server, portNumber); if (startTls) { // does not call stopTLS because it does not work ldapConnection.startTLS(); } ldapConnection.Bind(LdapConnection.Ldap_V3, login, password); if (startTls) { string errorMessage = ServerCertValidate(); if (!String.IsNullOrEmpty(errorMessage)) { ldapConnection.Disconnect(); throw new Exception(errorMessage); } } if (searchFilter == null) { ldapConnection.Disconnect(); return(null); } LdapSearchResults ldapSearchResults = ldapConnection.Search(disnguishedName, scope, searchFilter, attributes, false); while (ldapSearchResults.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = ldapSearchResults.next(); } catch (LdapException) { continue; } if (nextEntry != null) { entries.Add(nextEntry); } } ldapConnection.Disconnect(); return(entries); }
public void userList() { string LDAP_server = "localhost"; int ldapPort = 1920; string loginON = "uid=admin,ou=system"; string password = "******"; string searchBase = "ou=user,o=Company"; string searchFilter = "ObjectClass=UserLogin,Password,Name,TelNo,Email"; try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to " + LDAP_server); conn.Connect(LDAP_server, ldapPort); conn.Bind(loginON, password); string[] requiredAttri = { "cn", "sn", "uid" }; LdapSearchResults result = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, requiredAttri, false); while (result.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = result.next(); } catch (LdapException ex) { Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage); continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet ldapattri = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = ldapattri.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attri = (LdapAttribute)ienum.Current; string attriName = attri.Name; string attriVal = attri.StringValue; Console.WriteLine("\t" + attriName + "\tValue = \t" + attriVal); } } conn.Disconnect(); } catch (LdapException ex) { Console.WriteLine("LDAPconnection error:" + ex.LdapErrorMessage); return; } catch (Exception ex) { Console.WriteLine("LDAPconnection error:" + ex.Message); return; } }
static void DoSearch(string ldapHost, int ldapPort, string loginDN, string password, string searchBase, string searchFilter) { try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Console.WriteLine(attributeName + "value:" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
public ActionResult <HashSet <object> > GetUsersWithActiveDirectory([FromBody] SampekeyUserAccountRequest value) { var users = new HashSet <object>(); try { using (var connection = new LdapConnection { SecureSocketLayer = false }) { var _domain = Environment.GetEnvironmentVariable("AD_DDOMAIN"); var _domainServer = Environment.GetEnvironmentVariable("AD_DDOMAIN_SSERVER"); var _port = Environment.GetEnvironmentVariable("AD_PORT"); connection.Connect(_domainServer, int.Parse(_port)); connection.Bind($"{value.UserName}@{_domain}", value.Password); LdapSearchResults searchResults = connection.Search( Environment.GetEnvironmentVariable("BIND_DN"), LdapConnection.SCOPE_SUB, Environment.GetEnvironmentVariable("LDAP_FILTER"), null, false ); while (searchResults.hasMore()) { LdapEntry nextEntry = null; nextEntry = searchResults.next(); nextEntry.getAttributeSet(); var attr = nextEntry.getAttribute("mail"); if (attr == null) { users.Add(nextEntry.getAttribute("distinguishedName").StringValue); } else { users.Add(new{ Email = nextEntry.getAttribute("mail").StringValue, UserName = nextEntry.getAttribute("sAMAccountName").StringValue }); } } return(users); } } catch { return(users); } /* * HashSet<string> data = account.GetUsersWithActiveDirectory(value); * return Ok(data); */ }
public static string Credenciales(string usuario, string contraseña) { string[] prueba = new string[20]; string acceso = ""; try { string email = null; string rol = null; if (usuario != "u00000000" && usuario != "u12345678") { string ldapHost = "ldap.uca.es"; int ldapPort = 389; string loginDN = "CN=" + usuario + ",dc=uca,dc=es"; LdapConnection conn = new LdapConnection(); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, contraseña); if (conn.Bound) { string searchBase = "CN=" + usuario + ",dc=uca,dc=es"; string searchFilter = "tipodocumento=NIF"; LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_BASE, searchFilter, null, false); LdapEntry nextEntry = lsc.next(); email = nextEntry.getAttribute("mail").StringValue; rol = nextEntry.getAttribute("ou").StringValue; } } else { email = "*****@*****.**"; rol = "PDI"; } prueba = Insertar(7, usuario, null, null, null, null, null, null, null, null); acceso = prueba[0]; if (acceso == "0") { Insertar(10, usuario, email, rol, null, null, null, null, null, null); } if (acceso == "1") { acceso = "2"; } if (acceso == "0") { acceso = "1"; } } catch (LdapException e) { Console.WriteLine(e); } return(acceso); }
public AuthenticationResult AuthenticateUser(Credentials userInfo) { AuthenticationResult result = new AuthenticationResult(); try { LdapConnection conn = new LdapConnection(); conn.Connect(_LDAPConnectionInfo.Host, _LDAPConnectionInfo.Port); conn.Bind(userInfo.Username, userInfo.Password); string profileName = null; try { LdapSearchResults lsc = conn.Search(string.Empty, LdapConnection.SCOPE_SUB, "cn = " + userInfo.Username, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException) { continue; } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); LdapAttribute attribute = attributeSet.Cast <LdapAttribute>().Where(att => att.Name.Trim().ToUpper() == "PROFILE_NAME").SingleOrDefault(); if (attribute != null) { profileName = attribute.StringValue; } break; } } catch { } conn.Disconnect(); result.IsSuccess = true; result.UserProfile = new UserProfile(); result.UserProfile.Name = (profileName == null ? userInfo.Username : profileName); } catch (LdapException ex) { _logger.LogCritical(EventIds.AuthenticateUser, ex, nameof(LdapException)); result.ErrorMessage = ex.Message; result.IsSuccess = false; } catch (Exception ex) { _logger.LogCritical(EventIds.AuthenticateUser, ex, nameof(Exception)); result.ErrorMessage = ex.Message; result.IsServerError = true; result.IsSuccess = false; } return(result); }
/// <summary> /// Checks whether the entry exists in the Ldap directory or not /// </summary> /// <param name="lconn"> /// Connection used to communicate with directory /// </param> /// <param name="epath"> /// path of the entry /// </param> /// <returns> /// true of the entry exists in the Ldap directory /// false if entry doesn't exists /// </returns> private static bool CheckEntry(LdapConnection lconn, string epath) { LdapUrl lUrl = new LdapUrl(epath); string eDn = lUrl.getDN(); if (eDn == null) { eDn = String.Empty; } // rootDSE is a "virtual" entry that always exists else if (String.Compare(eDn, "rootDSE", true) == 0) { return(true); } string[] attrs = { "objectClass" }; try { LdapSearchResults lsc = lconn.Search(eDn, LdapConnection.SCOPE_BASE, "objectClass=*", attrs, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { // Exception is thrown, go for next entry throw e; } break; } } catch (LdapException le) { if (le.ResultCode == LdapException.NO_SUCH_OBJECT) { return(false); } else { throw le; } } catch (Exception e) { throw e; } return(true); }
/// <summary> /// Checks whether the entry with the specified Relative distinguised name /// exists or not. /// </summary> /// <param name="rdn"> Relative distinguished name of the entry</param> /// <returns>DirectoryEntry object of Entry if entry exists, /// Null if entry doesn't exist </returns> private DirectoryEntry CheckEntry(string rdn) { string Ofdn = null; DirectoryEntry cEntry = null; Ofdn = rdn + "," + Basedn; string[] attrs = { "objectClass" }; try { LdapSearchResults lsc = Conn.Search(Ofdn, LdapConnection.SCOPE_BASE, "objectClass=*", attrs, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); cEntry = new DirectoryEntry(Conn); LdapUrl Burl = new LdapUrl(_Bpath); LdapUrl curl = new LdapUrl(Burl.Host, Burl.Port, Ofdn); cEntry.Path = curl.ToString(); } catch (LdapException e) { // Exception is thrown, go for next entry throw e; } break; } } catch (LdapException le) { if (le.ResultCode == LdapException.NO_SUCH_OBJECT) { return(null); } else { throw le; } } catch (Exception e) { throw e; } return(cEntry); }
public IActionResult GetUsersLdap() { //Listas que utilizare para almacenar los usuarios de Ldap y sus respectivos atributos List <String> ldapusers = new List <String>(); List <String> atributos = new List <String>(); //Abrimos Socket contra el server LdapConnection ldapConn = new LdapConnection(); ldapConn.Connect("192.168.1.102", 389); //Definimos un filtro Ldap utilizado mas tarde, en este caso solo queremos los objetos tipo usuario string filter = "(ObjectClass=inetOrgPerson)"; try{ //Hacemos la busqueda LdapSearchResults query = ldapConn.Search("dc=fran,dc=local", LdapConnection.SCOPE_SUB, filter, null, false); //Recorremos la colecion de objetos Ldap while (query.hasMore()) { try { //Obtenemos el usuario iterado y obtenemos su DN y los metemos en la lista, hacemos lo mismo con //TODOS sus atributos(Por comodidad he hecho un toString) //En vez de recorrorerlos 1 a 1. LdapEntry nextEntry = query.next(); ldapusers.Add(nextEntry.DN); atributos.Add(nextEntry.getAttributeSet().ToString()); }catch (LdapException e) { //Si hubiera algun fallo el la obtencion del usuario iterado lo logeo y continuo Console.WriteLine("Error Entry: " + e.LdapErrorMessage); } } }catch (LdapException e) { //Si la busqueda ha fallado lo logueo y lanzo una excepcion para parar la app Console.WriteLine("Error Filtro: " + e.LdapErrorMessage); throw; } //Cargo las dos listas en la array dinamica de la vista ViewBag.ldapusers = ldapusers; ViewBag.atributos = atributos; return(View()); }
private bool checkAccess(string dnPerfil, string user, string password, LdapConnection ldap) { try { if (usuarioLdap.autenticado == false) { LdapSearchResults search = ldap.Search(dnPerfil, LdapConnection.SCOPE_SUB, null, null, false); LdapEntry entry = search.next(); LdapAttributeSet attribute = entry.getAttributeSet(); LdapAttribute attrib = attribute.getAttribute("uniquemember"); //if (attrib != null) //{ // usuarioLdap.autenticado = Array.Exists(attrib.StringValueArray, element => element.Contains(user.ToLower())); // if (usuarioLdap.autenticado) // usuarioLdap.perfil = attribute.getAttribute("cn").StringValue; // return usuarioLdap.autenticado; //} foreach (string usuario in attrib.StringValueArray) { if (usuario.Substring(3).Split(',').First().Equals(user)) { ldap.Bind(usuario, password); LdapSearchResults searchu = ldap.Search("cn=users,dc=network,dc=ctbc", LdapConnection.SCOPE_SUB, "uid=" + user, null, false); LdapEntry entryu = searchu.next(); LdapAttributeSet attributeu = entryu.getAttributeSet(); usuarioLdap.CPF = attributeu.getAttribute("CPF").StringValue; usuarioLdap.nomeAssociado = attributeu.getAttribute("DISPLAYNAME").StringValue; usuarioLdap.centroResultado = attributeu.getAttribute("DEPARTMENTNUMBER").StringValue; usuarioLdap.email = attributeu.getAttribute("MAIL").StringValue; usuarioLdap.tipo_usuario = attributeu.getAttribute("TIPOUSUARIO").StringValue; usuarioLdap.usuario = attributeu.getAttribute("CN").StringValue.ToLower(); usuarioLdap.perfil = attribute.getAttribute("cn").StringValue; usuarioLdap.autenticado = true; return(true); } } } } catch (LdapException) { throw new Exception("Usuário ou Senha Incorreta!"); } return(false); }
/// <summary> /// Search in AD for non-eRSA accounts created after a given date /// Only display selected attributes defined in _essentialProperties /// </summary> /// <param name="earliest"></param> public List <Dictionary <string, string> > Search(DateTime earliest) { string whenCreated = earliest.ToUniversalTime().ToString("yyyyMMddHHmmss.0Z"); Console.WriteLine("Local {0} to UTC {1}", earliest, whenCreated); string userFilter = HELPER.CreateFilter(whenCreated); List <Dictionary <string, string> > results = new List <Dictionary <string, string> >(); LdapSearchResults lsc = conn.Search(HELPER.SEARCH_BASE, LdapConnection.SCOPE_SUB, userFilter, HELPER.CREATION_PROPERTIES, false); int count = 0; while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); count++; } catch (LdapReferralException) { // Nothing really serious: constraints.ReferralFollowing = true this may not be needed // https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/b3u4u0n.html // https://technet.microsoft.com/en-us/library/cc978014.aspx continue; } catch (LdapException e) { Console.WriteLine("Move next error: {0}", e.ToString()); Console.WriteLine("Error message: " + e.Message); continue; } Console.WriteLine("\n" + nextEntry.DN); try { results.Add(GetProperties(nextEntry.getAttributeSet())); } catch (NullReferenceException ex) { Console.WriteLine("Not a qualified person account"); Console.WriteLine(ex.Message); } } return(results); }
// returns whether connection is e-dir or not. Also updates treeMatched with true or false depending on whether dirTreeName matches with the // tree name corresponding to connections's treeName public static bool IseDirectory(LdapConnection connection, string dirTreeName, out string treeName) { LdapAttribute attr = null; LdapEntry entry = null; bool eDirectory = false; treeName = null; LdapSearchResults lsc = connection.Search("", LdapConnection.SCOPE_BASE, "objectClass=*", null, false); while (lsc.hasMore()) { entry = null; try { entry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); continue; } LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { attr = (LdapAttribute)ienum.Current; string attributeName = attr.Name; string attributeVal = attr.StringValue; if (String.Equals(attributeName, "directoryTreeName")) { treeName = attributeVal; } if (String.Equals(attributeVal, "Novell, Inc.") == true) { eDirectory = true; } } } return(eDirectory); }
/// <summary> /// Authenticates by creating a bind. /// Connection exceptions will be thrown but invalid credential will return false /// </summary> /// <returns></returns> public bool Authenticate() { bool ret = false; LdapConnection conn = null; LdapConnection queryConn = null; try { //When using the proxy bind, authentications requires a user lookup and another bind. if (!string.IsNullOrEmpty(_config.BindingPw)) { LdapSearchResults authUser = LookupLdapUser(false, _username, out queryConn); if (authUser.hasMore()) { LdapEntry entry = authUser.next(); conn = Bind(_config.LdapHostname, entry.DN, _password); } else { _log.WarnFormat("No users matched search creteria for username '{0}'", _username); ret = false; } } else { conn = Bind(); } if (conn != null) { ret = conn.Bound; } } catch (LdapException x) { ret = false; if (x.ResultCode != LdapException.INVALID_CREDENTIALS) { throw; } } finally { UnBind(queryConn); UnBind(conn); } return(ret); }
private void PopulateGroupsForUserWithQuery(XDoc doc, string username, LdapConnection conn) { doc.Start("groups"); string searchFilter = string.Format(Dream.PhpUtil.ConvertToFormatString(_config.GroupMembershipQuery), username); //Build interesting attribute list List <string> attrs = new List <string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) { throw new ArgumentNullException("nextEntry"); } //Create xml from search entry doc.Start("group").Attr("name", GetNameFromDn(nextEntry.DN)).Start("ldap-dn").Value(nextEntry.DN).End().End(); } doc.End(); //groups }
/// <summary> /// Valida si el usuario tiene el rol asignado /// </summary> /// <param name="conn">Conexion activa del lda de novell</param> /// <param name="usuario">Id de usuario a validar</param> /// <returns>Si el usuario tiene asignado el rol</returns> private bool TieneRolAbax(LdapConnection conn, String usuario) { var rolBaseDN = ConfigurationManager.AppSettings.Get("DNBaseRolLDAPNovell"); LdapSearchResults gruposAbax = conn.Search(rolBaseDN, LdapConnection.SCOPE_BASE, "objectClass=*", null, false); bool tieneRolUsuario = false; while (gruposAbax.hasMore()) { LdapEntry grupoEntry = null; try { grupoEntry = gruposAbax.next(); LdapAttributeSet attributeSet = grupoEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; if (attributeName.Equals("member")) { foreach (var miembro in attribute.StringValueArray) { if (miembro.Contains(usuario)) { tieneRolUsuario = true; break; } } } } } catch (Exception e) { continue; } } return(tieneRolUsuario); }
public static string[] Query(string ADDomain) { List <string> results = new List <string>(); LdapConnection conn = new LdapConnection(); try { conn.Connect(ADDomain, LdapConnection.DEFAULT_PORT); conn.Bind(null, null); string searchBase = "ou=People,o=cwru.edu,o=isp"; string searchFilter = "(uid=bdm4)"; //string searchFilter = "(uid=" + data + ")"; /*LdapSearchQueue queue = * conn.Search(searchBase, LdapConnection.SCOPE_ONE, searchFilter, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); */ LdapSearchResults searchResults = conn.Search(searchBase, LdapConnection.SCOPE_ONE, searchFilter, new string[] { LdapConnection.NO_ATTRS }, true); while (searchResults.hasMore()) { LdapEntry nextEntry = null; nextEntry = searchResults.next(); results.Add(nextEntry.DN); } } catch (LdapException ldapex) { throw ldapex; } catch (Exception ex) { throw ex; } //conn.Disconnect(); return(results.ToArray()); }
/// <summary> /// Returns the list of ADS groups a person is in /// </summary> /// <param name="ADDomain">the FQDN Active Directory you wish to query, e.g ads.case.edu </param> /// <param name="userName">the persons username</param> /// <returns>A list of strings that contains all of thier ads groups.</returns> public static string[] GetUserGroupsFromADS(string ADDomain, string userName) { string[] results = { }; try { using (LdapConnection conn = new LdapConnection()) { conn.Connect(ADDomain, LdapConnection.DEFAULT_PORT); //conn.Bind(null, null); conn.Bind("nurs-ads-bdm4", ""); string searchBase = "ou=People,o=cwru.edu,o=isp"; string searchFilter = "(objectClass=*)"; //string searchFilter = "(uid=" + data + ")"; /*LdapSearchQueue queue = * conn.Search(searchBase, LdapConnection.SCOPE_ONE, searchFilter, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); */ LdapSearchResults searchResults = conn.Search(searchBase, LdapConnection.SCOPE_ONE, searchFilter, new string[] { LdapConnection.NO_ATTRS }, true); while (searchResults.hasMore()) { LdapEntry nextEntry = null; nextEntry = searchResults.next(); string cal = nextEntry.DN; } } } catch (LdapException ldapex) { throw ldapex; } catch (Exception ex) { throw ex; } return(results); }
/// <summary> /// 搜索DN中的用户 /// </summary> /// <param name="dn"></param> /// <returns></returns> public Dictionary <string, string> Search(string dn) { if (_isDisposed) { throw new ObjectDisposedException(nameof(LdapConnection)); } if (string.IsNullOrEmpty(_options.ManagerDn)) { throw new InvalidOperationException("The LDAP ManagerDn cannot be empty or null."); } _connection.Connect(_options.Hostname, _options.Port); try { _connection.Bind(_options.ManagerDn, _options.ManagerPassword); if (_connection.Bound) { Dictionary <string, string> list = new Dictionary <string, string>(); LdapSearchResults lsc = _connection.Search(dn, LdapConnection.SCOPE_SUB, _options.SearchFilter, new[] { "uid" }, false); while (lsc.hasMore()) { LdapEntry nextEntry = lsc.next(); list.Add(nextEntry.getAttribute("uid").StringValue.ToLower(), nextEntry.DN); } return(list); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { _connection.Disconnect(); } return(new Dictionary <string, string>()); }
public static string lookingForGroupDN(LdapConnection lc, String searchBase, string groupName) { string searchFilter = String.Concat("(&(objectCategory=Group)(cn=", groupName, "))"); string dn = ""; int searchScope = LdapConnection.SCOPE_SUB; String[] attrList = new String[] { "distinguishedName" }; LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; try { LdapSearchResults searchResults = lc.Search(searchBase, searchScope, searchFilter, attrList, false, cons); // time out value LdapEntry nextEntry = null; if ((nextEntry = searchResults.next()) != null) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; dn = attribute.StringValue; } } } catch (LdapException e) { Console.WriteLine("ERROR: Cannot find the group DN {0} (Maybe wrong groupname? ) ", groupName); throw new System.Exception(e.ToString()); } return(dn); }